var classReCache = {};
var _cur_mast = 0;
var _interval = 20000;
var _auto;
var _sections = ['', '#planning', '#look', '#flavor', '#memories']
String.prototype.strip = function(){
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
};

/*
 * JS Utility Functions
 */
 
_onReady = function(cb){
    if(/WebKit/i.test(navigator.userAgent)) { // safari	
        var _timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) {
                clearInterval(_timer);
                cb(); // call the onload handler
            }
        }, 10);		
    }else if(document.addEventListener)
        document.addEventListener("DOMContentLoaded", cb, false);
    else{
        document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
        var defer = document.getElementById("ie-deferred-loader");
        defer.onreadystatechange = function(){
         if(this.readyState == "complete")
             cb();
        };
    }
}

function _each(array, fn, scope){
    for(var i = 0, len = array.length; i < len; i++){
        if(fn.call(scope || array[i], array[i], i, array) === false){
            return i;
        };
    }
};

function _hasClass(el, className){
    return className && (' '+el.className+' ').indexOf(' '+className+' ') != -1;
};

function _addClass(el, className){
    _each([className], function(v) {
        el.className += (!_hasClass(el, v) && v ? " " + v : "");  
    });
    return el;
};

function _removeClass(el, className){
    if (el.className) {
        _each([className], function(v) {               
            el.className = el.className.replace(
                classReCache[v] = classReCache[v] || new RegExp('(?:^|\\s+)' + v + '(?:\\s+|$)', "g"), 
                " ");               
        });    
    }
    return el;
};

function _radioClass(el, className){
    _each(el.parentNode.childNodes, function(v) {
        if(v.nodeType == 1) {
            _removeClass(v, className);          
        }
    });
    return _addClass(el, className);
};

/*
 * Page Functionality
 */

var j = 0;
var _timer;
var _last;
var _sliding = false;
/*
 * @el      DOM Element The container
 * @index   The index of the desired destination masthead
 * @orig    The index of the originating masthead
 */
function _slide(el, index, orig){
    if(_sliding) clearTimeout(_timer);
    _sliding = true;
    _slide_to(el, index, orig, function(){
        _sliding = false;
    });
    return true;
};

/*
 * Recursive function for exponentially applying a style until
 * a specific threshold is met.
 */
function _slide_to(el, index, orig, cb){
    /* Calculate our current margin offset */
    var current = parseInt(el.style['left']) || 0;
    /* Calculate our intended goal (each masthead is 950 pixels in width) */
    var goal = -(index * 950);
    /* Calculate the necessary delta */
    var change = Math.abs(goal) - Math.abs(current);
    /* Apply the delta exponentially */
    var total = current - parseInt((change / 10));
    /* If we've reached a state where the delta isn't changing in each recursion,
     * just start using a delta of 1 */
    if(_last == total)
        total -= (index > orig ? 1 : -1);
    _last = total;
    /* Actually apply the style */
    el.style['left'] = total+'px';
    /* We're done! */
    if(change == 0){
        if(cb) cb();
        return clearTimeout(_timer);
    }
    function c(){
        _slide_to(el, index, orig, cb);
    }
    /* Continue to call recursively until the offset goal is met */
    _timer = setTimeout(c, 15);
} 

function _setMast(e, index){
    if(index == _cur_mast) return false;
        window.location.hash = _sections[index] || '#';
    
    /* Clear the automatic interval */
    clearInterval(_auto);
    
    _slide(document.getElementById('viewport'), index, _cur_mast);
    _radioClass(e.parentNode, 'current');
    _cur_mast = index;

    /* Reset the automatic interval */    
    _auto = setInterval(_autoSlide, _interval);    
    
    return false;
};

/* Utility function for manually selecting a section heading */
function _select(index){
    var items = [];
    _each(document.getElementsByTagName('a'), function(n){
        if(n.parentNode.parentNode == document.getElementById('topmenu'))
            items.push(n);
    });
    _setMast(items[index], index);    
};

/*
 * Periodically scroll automatically
 */
function _autoSlide(){
    _select((_cur_mast+1) % _sections.length);
};

_auto = setInterval(_autoSlide, _interval);

/* Read the anchor and select the correct masthead */
_onReady(function(){
    var hash = window.location.hash;
    if(hash){
        _each(_sections, function(s, i){
            if(s == hash){
                _select(i);
                _cur_mast = i;
                document.getElementById('viewport').style['left'] = -(i*950)+'px';
            }
        })
    }
});