// Javascript file for the About template
var scrollLeft = false;
/**************************************
 *
 *
 * Setup
 *
 *
 */

 // The width of the area the left point of the scrollbar can move in
 var scrollable_width = $('#scrollbar_outer').width() - $('#scrollbar').width();
 // The width of the inner scrolling content
 var inner_width = 0;
 // The width of the area the left point of the scrolling content can move in
 var max_left = 0;

/**************************************
 *
 *
 * CONTENT MOVEMENT-RELATED FUNCTIONS
 *
 *
 */

function get_max_left(){
    //alert(inner_width - $("#s_content").outerWidth() + 170);
    
    return inner_width - $("#s_content").outerWidth() + 170;
}

/**
 * Master function to control every part of the movement
 * 
 * @param scrollto Integer representing what pixel position the inner frame is moving to
 */
var scrolltoold = 0;
function scrollThings(scrollto) {
  // Make sure we have a properly formatted scrollto
  // within our expected range
  
  if(scrollLeft){
    //scrollto *= 1.22;
  }
  
  if(scrollto < 0) {
    scrollto = 0;
  }
  else if(scrollto > get_max_left()) {
    scrollto = get_max_left();
    
  }
  
  
  // Scroll the content
    $('#about_outer').scrollLeft(scrollto);
  
  // Scroll the scrollbar
  scrollTheBar(scrollto);
  
  // Highlight the appropriate section link
  highlightSectionLink();
}

/**
 * Controls the scrollbar position.
 * 
 * @param scrollto Integer representing what pixel position the inner frame is moving to
 */
function scrollTheBar(scrollto) {
  // Turn the pixel data into a percentage scrolled
  var percent = scrollto / get_max_left();
  
  // Figure out where the scrollbar left needs to be
  var scrollbar_left = Math.round(percent * scrollable_width);
  if(scrollbar_left < 0) {
    scrollbar_left = 0;
  }
  
  // Move the bar
  $('#scrollbar').css('left', scrollbar_left);

}

/**************************************
 *
 *
 * HASH-RELATED
 *
 *
 */

/**
 * Scroll to the given hash's section
 * 
 * @param hash JS URL hash string
 */
function scrollToHash(hash) {
  // Start off your mornings right with a clean hash
  hash = getSanitizedHash(hash);
  
  // Get the offset of the section
  var scrollto = getSectionX(getSectionByHash(hash));
  
  // Go!
  scrollThings(scrollto);
}

/**
 * Change the URL hash
 * 
 * @param hash JS URL hash string
 */
function changeHash(hash) {
  // Start off your mornings right with a clean hash
  //hash = getSanitizedHash(hash);
  //window.location.hash = hash;
}

/**************************************
 *
 *
 * SUBNAV-RELATED
 *
 *
 */

/**
 * Highlight the link for the current section
 */
function highlightSectionLink() {
  var section = getCurrentSection();
  
  var link = getLinkByHash(section.attr('id')); // Section IDs are its hash
  
  // Adjust the link's style
  makeLinkActive(link);
}

/**
 * Update the styles and hash for this link
 * 
 * @param link jQuery object for the link
 */
function makeLinkActive(link) {
  // Class jiggery
  $('#about_subsubnav a').removeClass('active');
  link.addClass('active');

  // Change the URL hash using this link's destination
  if(link.length && link.attr('href') != '#main_section') {
    changeHash(link.attr('href'));
  }
  // If this is the main section, just remove the hash
  else {
    changeHash('');
  }
}

/**
 * Event listener for subnav clicks
 */
function subnavClick() {
  var hash = $(this).attr('href');
  
  changeHash(hash);
  scrollToHash(hash);
  makeLinkActive($(this));
}

/**************************************
 *
 *
 * GETTERS, SETTERS
 *
 *
 */

/**
 * Get the element's X position in the scrolling content
 * 
 * @param section jQuery element for the section
 */
function getSectionX(section) {
  return section.position().left + getCurrentX();
}

/**
 * Get the current scroll position of the viewing area
 */
function getCurrentX() {
  return $('#about_outer').scrollLeft();
}

/**
 * Gets the section for the hash.
 * 
 * @param hash JS URL hash string
 */
function getSectionByHash(hash) {
  // Start off your mornings right with a clean hash
  hash = getSanitizedHash(hash);
  
  return $('[id='+hash+'_section]');
}

/**
 * Gets the subnav link for the hash.
 * 
 * @param hash JS URL hash string
 */
function getLinkByHash(hash) {
  // Start off your mornings right with a clean hash
  hash = getSanitizedHash(hash);
  
  return $('#about_subsubnav a[rel='+hash+']');
}

/**
 * Cleans up a JS URL hash
 * 
 * @param hash JS URL hash string
 */
function getSanitizedHash(hash) {
  return hash.replace(/_section$/, '').replace('#', '');
}

/**
 * Turn the scrollbar's % into the scrolling content's scroll px.
 * 
 * @param percent Float representing the percent the scrollbar has scrolled
 */
function getPXFromPercentage(percent) {
    
  return Math.round(percent * get_max_left());
}

/**
 * Gets the center of our viewport relative to the scrolling content.
 */
function getCurrentPosition() {
  var pos = getCurrentX();
  
  return pos + ($('#about_outer').width() / 2);
}

/**
 * Gets the section our viewport point is over.
 */
function getCurrentSection() {
  // The position of our viewport point.
  var pointer = getCurrentPosition();
  // The section we're looking for
  var section = false;
  
  // Get the sections
  var sections = $('.section');

  // if current position is 0 just return the first section
  if(getCurrentX() == 0) {
    var first = false;
    sections.each(function() {
	if(!first) { first = $(this); }
      });
    return first;
  }

  // Reverse the array, we need to approach the point backward
  sections = $(sections.get().reverse());
  
  // Cycle through each section
  sections.each(function() {
    // If the start of this section is before our pointer,
    // then it's the current section. This works because
    // we're approaching the pointer from its right.
    // --OR--
    // Select this section (it'll be the first) if we're as
    // far right as we can be.
     
    // the first one in the section will be the next section arrow, so continue
    if($(this).hasClass("next_arrow")) {
      // Continue
      return true;
    }

    if(pointer >= getSectionX($(this)) || getCurrentX() == get_max_left()) {
      section = $(this);
      
      // Break
      return false;
    };
    return '';
  });
  
  return section;
}

/**************************************
 *
 *
 * MOVEMENT RESPONDERS
 *
 *
 */

// Where drag movement starts
var startX = 0;
// Where the content is scrolled to
// at the beginning of a drag
var startPosX = 0;

/**
 * Set up the drag motion
 * 
 * @param event Drag Event
 */
function touchStart(event) {
  // Save where we started
  startX = event.targetTouches[0].pageX;
  // Save where the content is initially
  startPosX = getCurrentX();
}

/**
 * Handle the iPad drag motion
 * 
 * @param event Drag Event
 */
function touchMove(event) {
  // Don't do whatever you were about to do
  event.preventDefault();
  
  // Calculate the drag difference
  curX = event.targetTouches[0].pageX - startX;
  var scrollto = startPosX-curX;
  
  // Go!
  scrollThings(scrollto);
}



/**
 * Responds to the mouse wheel
 * 
 * @param e Event
 */
function MouseWheel(e) {
  // Setup stuff
  e = e ? e : window.event;
  var raw = e.detail ? e.detail : e.wheelDelta;
  scrollLeft = raw == 1 ? false: true;
  var normal = e.detail ? e.detail * -1 : e.wheelDelta / 400;
  
  // Safari is for some reason 40x faster
  //if(navigator.userAgent.toLowerCase().indexOf('safari') > -1 && navigator.userAgent.toLowerCase().indexOf('chrome') == -1) {
    //normal = normal / 40;
  //}
  
  // Set to a comfortable speed
  normal = normal * -30;
  var scrollto = $('#about_outer').scrollLeft() + normal;
  
  // Scroll!
  scrollThings(scrollto);

  // No one knows what this does
  return cancelEvent(e);
}

function scrollbarDrag() {
  var left = parseInt($('#scrollbar').css('left').replace('px', ''));
  var percent = left / scrollable_width;
  var scrollto = getPXFromPercentage(percent);
  
  scrollThings(scrollto);
}

/**************************************
 *
 *
 * SCROLLWHEEL EVENT HANDLING FRAMEWORK
 * (whatever you're looking for, it's
 * not in here. Do not modify.)
 *
 *
 */

/**
 * Hook event for scrollwheel events.
 * 
 * @param element ID of the element
 * @param eventName Name of the vent to hook
 * @param callback Function to call with the event
 */
function hookEvent(element, eventName, callback)
{
  if(typeof(element) == "string")
    element = document.getElementById(element);
  if(element == null)
    return;
  if(element.addEventListener)
  {
    if(eventName == 'mousewheel')
      element.addEventListener('DOMMouseScroll', callback, false);  
    element.addEventListener(eventName, callback, false);
  }
  else if(element.attachEvent)
    element.attachEvent("on" + eventName, callback);
}

/**
 * Unhook event for scrollwheel events.
 * 
 * @param element ID of the element
 * @param eventName Name of the vent to unhook
 * @param callback Function to call with the event
 */
function unhookEvent(element, eventName, callback)
{
  if(typeof(element) == "string")
    element = document.getElementById(element);
  if(element == null)
    return;
  if(element.removeEventListener)
  {
    if(eventName == 'mousewheel')
      element.removeEventListener('DOMMouseScroll', callback, false);  
    element.removeEventListener(eventName, callback, false);
  }
  else if(element.detachEvent)
    element.detachEvent("on" + eventName, callback);
}

/**
 * For the scrollwheel events.
 * 
 * @param e Event
 */
function cancelEvent(e)
{
  e = e ? e : window.event;
  if(e.stopPropagation)
    e.stopPropagation();
  if(e.preventDefault)
    e.preventDefault();
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
}

