// **********************************************
// Throll: Toms Horizontal Scroll 
// Developer: Tom Elders
// Contact: him@tomelders.com
// **********************************************
// File: throll.1.0.js
// Description: 
// CSS and JS horizontal scrolling that doesn't
// break the browers native functionality. 
//
// Copyright 2010, Tom Elders
//
// **********************************************

var grabberClicked = false;
var dragStart;
var ratio;
var scrollBound;
var totalWidth = 0;

// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

$(document).ready(function(){

    $("#projects").width(getTotalWidth());
    setup();
    $("#grabber").mousedown(startScroll);
    $(document).mouseup(endScroll);
    $("#viewport").scroll(positionGrabber);
    $(window).resize(setup);


});

function getTotalWidth(){

    $(".project").each(function(){

        totalWidth += $(this).width();
        totalWidth += parseInt($(this).css("marginLeft")) * 2;

    })

    return totalWidth;

}

// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function setup(){
    ratio = $("#viewport").width() / $("#projects").width();

    // grabber width
    $("#grabber").width( $("#scrollbar").width() * ratio );
    scrollBound = $("#scrollbar").width() - $("#grabber").width();

    // incase the user resizes the window, position the grabber accordingly
    positionGrabber();
}

// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function startScroll(event){
    $(document).bind('mousemove', scroll);
    var position = $("#grabber").position();
    dragStart = event.pageX - position.left;
}

// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function endScroll(event){
    $(document).unbind('mousemove', scroll);
}

// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function scroll(event){ 
    var newPos = event.pageX - dragStart;

    // bounds
    newPos = (newPos > 0) ? newPos : 0;
    newPos = (newPos < scrollBound) ? newPos : scrollBound;

    viewportPos = ( $("#projects").width() * ( newPos / $("#scrollbar").width() ) );
    $("#viewport").scrollLeft(viewportPos);
    $("#grabber").css("left", newPos);

}

// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function positionGrabber(event){
    var grabberPos = $("#scrollbar").width() * ($("#viewport").scrollLeft() / $("#projects").width());
    $("#grabber").css("left", grabberPos);
}