(function($) {

    $.fn.slider = function(settings) {

        var settings = $.extend({
	    time: [1000, 1000],
            slideTo: null,
            navigation: null
	}, settings),

        slider = {},

        _init = function(obj) {

            slider = {
                container: $(obj),
                input: $(obj).children('input[name="sliderPointer"]'),
                slides: $(obj).children('.slide'),
                buttons: $(obj).children('.btn'),
                navigation: $(settings.navigation),
                overhang: $(settings.navigation).children('.sliderOverhang')
            },

            ($(slider.container).hasClass('auto')) ? _auto(settings.time[0]) : null;

            $(slider.buttons).unbind('click').bind('click', function() {

                if ($(this).hasClass('btnPrevious')) {
                    _slide('previous', false);
                } else if ($(this).hasClass('btnNext')) {
                    _slide('next', false);
                }

            });

            $(slider.overhang).children('a').unbind('click').bind('click', function() {
                var className = $(this).attr('class').split(' ');
                var slideTo = Number(className[0].replace('slideTo_', ''));
                _slide(slideTo, false);
            });

            (settings.slideTo) ? _slide(settings.slideTo, true) : null;

            if ($(slider.overhang).width() > $(slider.navigation).width()) {
                $(slider.buttons).show();
            }

        },

        _slide = function(slideTo, strict) {

            var pointer = Number($(slider.input).val());

            var slides = $(slider.slides).length;

            var next;

            switch (slideTo) {

                case 'next':
                    next = (pointer == slides) ? 1 : pointer+1;
                break;

                case 'previous':
                    next = (pointer == 1) ? slides : pointer-1;
                break;

                default:
                    next = slideTo;
                break;

            }

            if (next != pointer && next <= slides) {

                $(slider.input).val(next);

                $(slider.container).children('.slide:eq('+(pointer-1)+')').removeClass('top');

                if (strict) {

                    $(slider.container).children('.slide:eq('+(next-1)+')').addClass('top').show();

                    $(slider.container).children('.slide:eq('+(pointer-1)+')').hide();

                } else {

                    $(slider.container).children('.slide:eq('+(next-1)+')').addClass('top').fadeIn(settings.time[1], function() {
                        $(slider.container).children('.slide:eq('+(pointer-1)+')').hide();
                    });

                }

                if (settings.navigation) {

                    var navigation = $(slider.navigation).width();

                    var middle = navigation/2;

                    var overhang = $(slider.overhang).width();

                    var left = $(slider.overhang).children('a:eq('+(next-1)+')').offset().left-$(slider.navigation).offset().left;

                    var adjust = $(slider.overhang).children('a:eq('+(next-1)+')').width()/2;

                    if (overhang > navigation) {

                        var pos = Number($(slider.overhang).css('left').replace('px', ''));

                        if (left < middle) {
                            pos += middle-left-adjust;
                        } else {
                            pos += middle-left-adjust;
                        }

                        if (pos > 0) {
                            pos = 0;
                        } else if (pos < (navigation-overhang)) {
                            pos = navigation-overhang;
                        }

                        if (strict) {

                            $(slider.overhang).css({
                                left: pos+'px'
                            });

                        } else {

                            $(slider.overhang).animate({
                                left: pos+'px'
                            });

                        }

                    }

                }

            }

        },

        _auto = function(time) {

            setTimeout(function() {

                _slide('next', false);

                _auto(time);

            }, time);

        };

        _init(this);

    };

  $.tweet = function(user, number, callback) {

    var tweets = [],
        tweet,
        exp1 = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
        exp2 = /@([_a-z0-9]+)/ig

    $.getJSON('http://twitter.com/statuses/user_timeline.json?screen_name='+user+'&count='+number+'&callback=?', function(data) {

      $.each(data, function() {

        tweet = this.text;
        
        tweet = tweet.replace(exp1, '<a href="$1">$1</a>').replace(exp2, "<a href=http://twitter.com/$1>@$1</a>");

        tweets.push(tweet);

      });

      callback(tweets);
      
    });
    
  };

  $.highlightProject = function(id) {

    $('.projectList a').removeClass('active');

    if (id) {
      $('#project_'+id+' a').addClass('active');
    } else {
      $('.projectList:eq(0) a').addClass('active');
    }

  };

  $.highlightHistory = function(id) {

    $('.historyList li').removeClass('active');

    if (id) {
      $('#'+id).addClass('active');
    } else {
      $('.historyList li:eq(0)').addClass('active');
    }

  };
  
  $.loadHistoryContent = function(id) {

    if (id) {

      var $this = $('#'+id),

          title = $this.children('h3').text(),
          content = $this.children('input').val(),

          html = '<p><strong>'+title+'</strong></p>'+content;

      $('#ajax').html(html);

    }

  }

  $.scrollToAnchor = function(id, hash, padding, duration, easing) {

    if (id) {

      location.hash = '#'+hash;

      $('html, body').animate({
        scrollTop: $('#'+id).offset().top-padding
      }, duration, easing);

    }
	
  };

})(jQuery);

$(function() {

  var setPageSize = function() {

    var $stage = $('#stCont'),
        $content = $('#ctCont'),
        $meta = $content.find('.meta'),

        pageHeight = $('#dcCont').height(),
        height = $(window).height(),
        newHeight = height-200-27-1-6;

    if (height > pageHeight) {
        
      if ($stage.length == 1) {
        newHeight -= 301-3;
      }

      $content.height(newHeight);
      $meta.height($meta.height()-38);

    }

  };

  setPageSize();

  var twitterUser = $('input[name="twitter"]').val();

  $.tweet(twitterUser, 1, function(tweets) {
    var html;
    if (tweets[0]) {
      html = '<p>'+tweets[0]+'</p><a href="http://twitter.com/'+twitterUser+'" class="more-link">» Follow us on Twitter</a>';
    } else {
      html = '';
    }
    $('.tweets').html(html);
  });

  Cufon.set('fontFamily', 'ITC Lubalin Graph Book').replace('#stCont h1')('#ctCont .stage h1');
  Cufon.set('fontFamily', 'Knockout Full Heviweight').replace('#stCont h2')('#ctCont .stage h2')('#ctCont h1.headline');

  var timeout = null,
  openNav = null;

  $('#mainNav li.nav').hover(function() {

    if ($(this).children('ul').length) {

      clearTimeout(timeout);

      timeout = null;

      var nav = $(this).children('a').attr('class');

      if (openNav != nav) {

        openNav = nav;

        $('#mainNav li.nav ul:visible').hide();

        $(this).children('ul').show();

      }

    }

  }, function() {

    if ($(this).children('ul').length) {

      var $this = $(this);

      timeout = setTimeout(function() {

        $this.children('ul').hide();

        openNav = null;

      }, 250);

    }

  });

  $('.projectList').each(function() {
	
    var id = $(this).attr('id');

    $(this).attr('id', 'project_'+id);

  });

  $('.projectList a').bind('mouseover click', function(e) {

    e.preventDefault();

    var id = $(this).attr('href').substr(1);

    switch (e.type) {

      case 'mouseover':
        $.highlightProject(id);
      break;

      case 'click':
        $.scrollToAnchor('project_'+id, id, 25, 'slow');
      break;

    }

  });

  $('.historyList li').each(function() {

    var id = $(this).attr('id');

    $(this).attr('id', 'year_'+id);

  });

  $('.historyList li').bind('mouseover click', function(e) {

    var id = $(this).attr('id'),
        year = id.replace('year_', '');

    switch (e.type) {

      case 'mouseover':
        $.highlightHistory(id);
      break;

      case 'click':

        $.loadHistoryContent(id);

        $.scrollToAnchor(id, year, 25, 'slow');
      break;

    }

  });

  $('.sliderContainer').slider({
    time: [3000, 1000]
  });

  $(window).resize(function() {
    setPageSize();
  });

});
