$(document).ready(function() {
  var $hb =   $('#home-banner');
  var totalWidth = 0;
  $hb
    .find('img').map(function() {
      totalWidth += $(this).width() + 22;
      return totalWidth;
    })
  .end().end()
    .find('.feature-title')
    .css({
      opacity: '.7',
      backgroundColor: '#000'
    })
  .end();
  $hb.find('.scroll-content').width(totalWidth);
	var scrollPane = $('.scroll-pane');
	var scrollContent = $('.scroll-content');
	
	//build slider
	$('.scroll-bar-wrap').css('opacity', 0.6);
	var scrollbar = $(".scroll-bar").slider({
		stop:function(e, ui){
			if( scrollContent.width() > scrollPane.width() ) { 
			  scrollContent.animate({'marginLeft': Math.round( ui.value / 100 * ( scrollPane.width() - scrollContent.width() )) + 'px'}, 200);
			} else { 
			  scrollContent.animate({'marginLeft': 0}, 200); 
			}
		}
	});
	
	//append icon to handle
	var handleHelper = scrollbar.find('.ui-slider-handle')
	.mousedown(function(){
		scrollbar.width( handleHelper.width() );
	})
	.mouseup(function(){
		scrollbar.width( '100%' );
	})
	.append('<span class="ui-icon ui-icon-grip-dotted-vertical"></span>')
	.wrap('<div class="ui-handle-helper-parent"></div>').parent();
	
	//change overflow to hidden now that slider handles the scrolling
	scrollPane.css('overflow','hidden');
	
	//size scrollbar and handle proportionally to scroll distance
	function sizeScrollbar(){
    // var remainder = scrollContent.width() - scrollPane.width();
    // var proportion = remainder / scrollContent.width();
    // var handleSize = scrollPane.width() - (proportion * scrollPane.width());
    // scrollbar.find('.ui-slider-handle').css({
    //  width: handleSize,
    //  'margin-left': -handleSize/2
    // });
    // handleHelper.width('').width( scrollbar.width() - handleSize);
	  handleHelper.width('').width( scrollbar.width() - 30);
  
	}
	
	
	//reset slider value based on scroll content position
	function resetValue(){
		var remainder = scrollPane.width() - scrollContent.width();
		var leftVal = scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'),10);
		var percentage = Math.round(leftVal / remainder * 100);
		scrollbar.slider("value", percentage);
	}
	//if the slider is 100% and window gets larger, reveal content
	function reflowContent(){
			var showing = scrollContent.width() + parseInt( scrollContent.css('margin-left'), 10 );
			var gap = scrollPane.width() - showing;
			if(gap > 0){
				scrollContent.css('margin-left', parseInt( scrollContent.css('margin-left'), 10 ) + gap);
			}
	}
	
	//change handle position on window resize
	$(window)
	.resize(function(){
			resetValue();
			sizeScrollbar();
			reflowContent();
	});
	//init scrollbar size
	setTimeout(sizeScrollbar,10);//safari wants a timeout
});
