/*! http://mths.be/oninput by @mathias */
jQuery.fn.input = function(fn) {
  var $this = this;
  return fn
    ?
      $this.bind({
        'input.input': function(event) {
          $this.unbind('keydown.input');
          fn.call(this, event);
        },
        'keydown.input': function(event) {
          fn.call(this, event);
        }
      })
    :
      $this.trigger('keydown.input');
};

/*!
 * Simplest jQuery Slideshow Plugin v1.0.0
 * @link http://github.com/mathiasbynens/Simplest-jQuery-Slideshow
 * @author Mathias Bynens <http://mathiasbynens.be/>
 */
$.fn.slideshow = function(options) {
  options = $.extend({
    timeout: 6000,
    speed: 400 // 'normal'
  }, options);
  return this.each(function() {
    var $elem = $(this);
    $elem.children().eq(0).appendTo($elem).show();
    setInterval(function() {
      $elem.children().eq(0).hide().appendTo($elem).fadeIn(options.speed);
    }, options.timeout);
  });
};

// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!

// callback function is passed the last image to load
//   as an argument, and the collection as `this`

$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      
  elems.bind('load',function(){
      if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }  
  }); 

  return this;
};

$.fn.tooltip = function(selector) {
  selector || (selector = '.popup');
  return this.each(function() {
    var $this = $(this),
    $popup = $(selector, $this).addClass('popupInstance');
    $this.hover(function() {
      $popup.fadeToggle(300);
    });
  });
};

$(function() {

  var $masonryList = $('.masonryList'),
      $gmap = $('#gmapHolder'),
      $items = $('#items'),
      $itemLinks = $items.length && $('a', $items),
      $currentItem = $('#currentItem').children(),
      $hashItem,
      $message = $('#message, #comment'),
      i = 0,
      msgID = location.href + '-message',
      storage = (function() {
        try {
          var storage = window.localStorage;
          return storage.getItem && storage;
        } catch(e) {}
      }());

  // Add windows class so we can style based on Helvetica Neue Condensed or Arial
  if (navigator.platform == 'Win32') {
    $('body').addClass('windows');
  }
  
  if (navigator.platform == 'iPad') {
    $('body').addClass('iPad');
  }

  if ($('body').width() > 992) {
    $('img', $masonryList).imagesLoaded(function() {
      $masonryList.masonry();
    });
  };

  // Netlash tooltip
  $('.invokePopup').removeAttr('title').tooltip();

  // <textarea> in contact/comment form
  // Assume only 1 <textarea> per document
  if (storage) {
    $message.each(function() {
      if (!this.value) {
        this.value = storage[msgID] || '';
        $message.trigger('change');
      }
    }).input(function() {
      storage[msgID] = this.value;
    }).parentsUntil('form').parent().submit(function() {
      storage.removeItem(msgID);
    });
  }

  // Branding and identity
  if ($items.length) {
    $itemLinks.click(function(e) {
      e.preventDefault();
      $('.selected', $items).removeClass();
      $currentItem.hide();
      $currentItem.eq( $(this).addClass('selected').parent().index() ).fadeIn(200);
      if (window.history && history.pushState && i++ > 0) {
        history.pushState({}, this.innerHTML, this.hash);
      }
    });

    $(window).bind('load hashchange', function() {
      if (location.hash) {
        $hashItem = $currentItem.filter(location.hash);
        if ($hashItem.length) {
          $itemLinks.eq( $hashItem.index() ).click();
        } else if (!i) {
          $itemLinks.first().click();
        }
      } else {
        $itemLinks.first().click();
      }
    });
  }

  // Show big images in modal if screen height is sufficient
  if ($('body').height() > 860) {
    $('.reveal-modal').removeClass('medium');
  };

  // About: image rotator

  if ($('body').width() > 992) {
    $('#photos').slideshow();
  }

  // Smooth scroll
  $('#content').smoothScroll(300);

  /* Handle right-click on logo */
  $('#site-title a').bind('contextmenu', function(event) {
    $('#logoDownload').reveal();
    event.preventDefault();
  });

  // Responsive dropdown

  // Create the dropdown base
  $("<select />").appendTo("#header");

  // Create default option "Go to..."
  $("<option />", {
     "selected": "selected",
     "value"   : "",
     "text"    : "Go to..."
  }).appendTo("#header select");

  // Populate dropdown with menu items
  $("#header ul a").each(function() {
   var el = $(this);
   $("<option />", {
       "value"   : el.attr("href"),
       "text"    : el.text()
   }).appendTo("#header select");
  });

  $("#header select").change(function() {
    window.location = $(this).find("option:selected").val();
  });

  $("#content").fitVids();

});

// Google Analytics
var _gaq = [['_setAccount', 'UA-6948763-1'], ['_trackPageview'], ['_trackPageLoadTime']];
(function(d, t) {
 var g = d.createElement(t),
     s = d.getElementsByTagName(t)[0];
 g.src = '//www.google-analytics.com/ga.js';
 s.parentNode.insertBefore(g, s);
}(document, 'script'));


