$(function() {
  navigation.init();
  if ($('#portfolio .item').length) $('#portfolio .item').portfolio_item();
  if ($.browser.msie && jQuery.browser.version.substr(0,1) == "6") {
    // fix png's ie6
    if ($('#teasers').length) DD_belatedPNG.fix("#teasers img");
    DD_belatedPNG.fix("#current, #current div");
  }
  featured.init();
})

var featured = new(function() {
  var base = this;
  var index = 0, width, length, selected_index = null, timeout_id;
  
  base.init = function() {
    if ($('#teasers').length == 0) return;
    base.teaser_container = $('#teasers')
    base.teasers = base.teaser_container.children();
    
    //setup
    width = base.teaser_container.width();
    length = base.teasers.length;
    if (length > 1) {
      base.setupButtons();
      base.teasers.not(':first-child').css('left', width);
      //start rotating
      base.slideInComplete();
    }
  }
  
  base.setupButtons = function() {
    $('#visual').append('<ul id="teaser-selector"></ul>');
    base.selector = $('#teaser-selector');
    base.teasers.each(function() {
      $(this).attr('id', 'showcase-' + $(this).index());
      base.selector.append('<li><a href="#showcase-'+ $(this).index() +'"></a></li>')
    })
    base.setSelected();
    base.selector.find('a').click(base.onSelectorClick);
  }
  
  base.onSelectorClick = function(event) {
    event.preventDefault();
    if ($(this).parent().hasClass('selected')) return;
    selected_index = $(this).attr('href').split('-')[1];
    clearTimeout(timeout_id);
    $('#teasers .teaser:eq(' + index + ')').stop();
    base.rotate();
  }
  
  base.rotate = function() {
    base.slideOut()
  }
  
  base.slideOut = function() {
    $('#teasers .teaser:eq(' + index + ')').animate({ left: width }, base.slideOutComplete);
  }
  
  base.slideOutComplete = function() {
    base.hideCurrent();
    base.unsetSelected();
    if (selected_index !== null) {
      index = selected_index;
      selected_index = null;
    } else {
      index++; if (index >= length) index = 0;
    }
    base.showCurrent();
    base.setSelected();
    base.slideIn();
  }
  
  base.slideIn = function() {
    $('#teasers .teaser:eq(' + index + ')').animate({ left: 0 }, base.slideInComplete);
  }
  
  base.slideInComplete = function() {
    timeout_id = setTimeout(base.rotate, 8000);
  }
  
  base.showCurrent = function() {
    $('#teasers .teaser:eq(' + index + ')').show();
  }
  
  base.hideCurrent = function() {
    $('#teasers .teaser:eq(' + index + ')').hide();
  }
  
  base.setSelected = function() {
    base.selector.find('li:eq(' + index + ')').addClass('selected');
  }
  
  base.unsetSelected = function() {
    base.selector.find('li:eq(' + index + ')').removeClass('selected');
  }
})();

// requires jquery and the beautiful simple motion.js (http://lab.gracecode.com/motion/) for synchronous animations
var navigation = new (function() {
  var base = this;
  
  var url = null, navigation_paths = [], animation_state = 0, timeout_id;
  
  base.init = function() {
    base.navigation     = $('#navigation');
    base.navigation_a   = base.navigation.find('a');
    base.slider         = base.buildSlider();
    base.slider_div     = base.slider.find('div');
    base.slider_ul      = base.slider.find('ul');
    base.slider_a       = base.slider.find('a');
    base.current        = base.getCurrent();
    base.active         = base.current;
    
    base.external_a     = $('#header a.logo, #visual .cta, #footer .copyright a');
    
    // setup motion
    base.motion = new Motion('backOut', 500);
    base.motion.onComplete = base.onMotionComplete;
    
    // store paths
    base.storePaths();
    
    $(window).load(base.setupSlider);
  }
  
  // =================
  // = Setup methods =
  // =================
  
  base.buildSlider = function() {
    base.navigation.parent().append('<div id="slider"><div>' + base.navigation.html() + '</div></div>');
    return $('#slider').css({ left: '-1000em' });
  };
  
  base.getCurrent = function() {
    var current = base.navigation.find('li.current-menu-item a');
    if (current.length == 0)
      current = base.navigation.find('li:first').addClass('current-menu-item').find('a');
    return current;
  };
  
  base.storePaths = function() {
    base.navigation_a.each(function() {
      navigation_paths.push($(this).attr('href').replace(base.getBaseUrl(), '').replace(/\//gi, ''));
    })
  };
  
  // ==================
  // = Helper methods =
  // ==================
  
  base.getBaseUrl = function() {
    var host = document.location.host;
    var protocol = document.location.protocol;
    return protocol + '//' + host;
  };
  
  base.getOffsetsAndPositions = function(element, with_slider) {
    var o = {};
    o.element       = {}
    o.element.left  = element.position().left - 5; // padding / 2
    o.element.width = element.outerWidth();
    
    if (with_slider) {
      o.slider         = {};
      o.slider_ul      = {};
      o.slider.left    = base.slider.position().left;
      o.slider.width   = base.slider.width();
      o.slider_ul.left = base.slider_ul.position().left;
    }
    return o;
  };
  
  base.setUrl = function() {
    if (url !== null) document.location.href = url;
  };
  
  base.enableEvents = function() {
    base.navigation_a.click(base.onClick);
    base.navigation_a.mouseenter(base.moveSlider);
    base.slider_a.click(base.onClick);
    base.slider.mouseenter(base.onSliderEnter);
    base.slider.mouseleave(base.onSliderLeave);
    base.external_a.mouseenter(base.moveSliderExternal);
    base.external_a.mouseleave(base.restoreSliderExternal);
  }
  
  base.disableEvents = function() {
    base.navigation_a.unbind('mouseenter', base.moveSlider);
    base.slider.unbind('mouseenter', base.onSliderEnter);
    base.slider.unbind('mouseleave', base.onSliderLeave);
    base.external_a.unbind('mouseenter', base.moveSliderExternal);
    base.external_a.unbind('mouseleave', base.restoreSliderExternal);
    

    base.navigation_a.unbind('click', base.onClick).click(base.onClickDisabled);
    base.slider_a.unbind('click', base.onClick).click(base.onClickDisabled);
    base.external_a.unbind('click', base.onClick).click(base.onClickDisabled);
  };
  
  // ===================
  // = Event Callbacks =
  // ===================
  
  // callback onLoad
  base.setupSlider = function() {
    base.jumpSlider(base.current);
    base.enableEvents();
  };
  
  // callback navigation links enter
  base.moveSlider = function() {
    animation_state = 1; // moving towards
    base.animateSlider($(this));
  };
  
  // callback external links enter
  base.moveSliderExternal = function() {
    var path = $(this).attr('href').replace(base.getBaseUrl(), '').replace(/\//gi, '').replace(/#.*$/, '');
    $.each(navigation_paths, function(index, value) {
      if (path == value) {
        clearTimeout(timeout_id);
        base.moveSlider.call(base.navigation.find('a:eq(' + index + ')'));
        return false;
      }
    });
  };
  
  // callback timeout
  base.restoreSlider = function() {
    animation_state = 3; // moving backwards
    base.animateSlider(base.current);
  }
  
  // callback external links leave
  base.restoreSliderExternal = function() {
    base.restoreSlider();
  };
  
  // callback for nav, slider and external links
  base.onClick = function(event) {
    event.preventDefault();
    if (animation_state == 0) return;
    base.disableEvents();
    clearTimeout(timeout_id);
    url = $(this).attr('href');
    if (animation_state == 2) base.setUrl();
  };
  
  // callback for disabled links
  base.onClickDisabled = function(event) {
    event.preventDefault();
  };
  
  // callback slider enter;
  base.onSliderEnter = function() {
    clearTimeout(timeout_id);
  };
  
  // callback slider leave;
  base.onSliderLeave = function() {
    clearTimeout(timeout_id);
    timeout_id = setTimeout(base.restoreSlider, 1000);
  };
  
  // ====================
  // = Movement methods =
  // ====================
  
  base.jumpSlider = function(element) {
    base.motion.stop();
    base.active = element;
    var o = base.getOffsetsAndPositions(element, false);
    
    base.slider.css(o.element);
    base.slider_ul.css({ left: -o.element.left });
  };
  
  base.animateSlider = function(element) {
    base.motion.stop();
    base.active = element;
    var o = base.getOffsetsAndPositions(element, true);
    
    // motion handler
    base.motion.onTweening = function() {
      // parallel animation
      base.slider.css({
        left:  this.equation( o.slider.left, o.element.left ),
        width: this.equation( o.slider.width, o.element.width )
      })
      base.slider_ul.css({
        left:  this.equation( o.slider_ul.left, -o.element.left )
      })
    };
    
    base.motion.start();
  };
  
  base.onMotionComplete = function() {
    if (animation_state == 1) animation_state = 2;
    if (animation_state == 3) animation_state = 0;
    base.setUrl();
  };
})();
