var doScroll = function(element, url) {
    if ( !( element = $(element) ) ) { return; }
    var scrollingDiv = $('MainContent');
    var delta        = Position.positionedOffset(element)[0] - scrollingDiv.scrollLeft;
    var newURL =  url + '#' + element.id;
    $$('#Navigation li').each(function(li) {
        var a = li.down('a');
        if (!a || a.href != newURL) {
            li.removeClassName('active');
        }
        else {
            li.addClassName('active');
        }
    });
    new Effect.Scroll(scrollingDiv, { x: delta, duration: 1.5, afterFinish: function(){location.href=newURL} });
    return 1;
};       
var initPage = function() {
    var url = location.href.split('#');
    if (url[1]) { doScroll(url[1], url[0]); } 
}

document.observe('dom:loaded', function(event){

    //set navigation anchor links to do scroll
    $$('#Navigation a[href*="#"]').each(function(anchor){
        anchor.observe('click', function(event) {
          var url = this.href.split('#');
          var success = doScroll(
            $$('a[name~="#{href}"]'.interpolate({href: url[1]})).first(),
            url[0]
          );
          if (success) { Event.stop(event); }        
        });
    });
    
    // init page if the request is for a nav link
    if (/KHTML|WebKit/i.test(navigator.userAgent)) { // safari needs a beat
      setTimeout(initPage, 100 );
    }
    else {
      initPage();
    }
});

var Rosy ={
  numImages : {
    'home': 5
  },
  getRandom : function(maxNum) {
    if (Math.random && Math.round) {
      return ( Math.round(Math.random()*(maxNum-1)) )+1;
    }
    var today=new Date();
    var hours=today.getHours();
    var mins=today.getMinutes();
    var secn=today.getSeconds();
    if (hours==19) { hours=18; }
    return (((hours+1)*(mins+1)*secn)%maxNum)+1;
  },
  rotateImg:function(slug){
    if (!slug || !Rosy.numImages[slug]) { slug = 'home'; }
    var total = Rosy.numImages[slug];
    var num = (total ? Rosy.getRandom(total) : 1).toString();
    var html = '<img src="images/rotate/' + slug + '_' + num + '.jpg" alt="" />';
    document.write(html);
  }
};
