/* Author: Evident Web Design */

$(document).ready(function(){
  var tabContainers = $('#tabContainer > div');
  var tabNavs = $('#tabNav a');
  
  //Function to change the url without reloading the entire page
  tabNavs.click(function(){
    var href = $(this).attr( "href" );
    $.bbq.pushState( href );
    return false; // Prevent the default click behavior.
  });
  
  //Function which changes the tab contents on hashchange
  $(window).bind('hashchange', function (e) {
    var hash = e.fragment;
    
    tabNavs.removeClass('current');
    
    if (hash === ''){
        tabContainers.filter('.current').fadeOut('fast',function(){ 
            tabContainers.removeClass('current');
            tabContainers.filter(':first').fadeIn('fast',function(){ 
                $(this).addClass('current');
            });
        });
        tabNavs.filter(':first').addClass('current');
    }else{
        tabContainers.filter('.current').fadeOut('fast',function(){ 
            tabContainers.removeClass('current');
            tabContainers.filter('#'+hash).fadeIn('fast',function(){ 
                $(this).addClass('current');
            });
        });
        tabNavs.filter('[href="#'+hash+'"]').addClass('current');
    }
  });
  
  $(window).trigger("hashchange");
  
  //Function cycles through the slides on the home page
  $(function() {
    var $interval = 3000;
    setInterval( "slideSwitch()", $interval );
  });
});


function slideSwitch() {
	var active = $('#fadeshow img.active'),
		next = active.next().length ? active.next() : $('#fadeshow img:first');
  
	//modify the attributes of the img
	if(next.attr('id').length){
		next.attr({'src':next.attr('id')}).removeAttr('id');
	}

	//execute once the image loads
	next.imagesLoaded(function(){ 
		active.addClass('last-active');

		next.css({opacity: 0.0}).addClass('active')
		.animate({opacity: 1.0}, 1000, function(){
				active.removeClass('active last-active');
		});
	});
}



// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// callback function is passed the last image to load
//   as an argument, and the collection as `this`

$.fn.imagesLoaded = function(callback){
	var elems = this.find('img'),
		len   = elems.length,
		_this = this;
  
	if( !elems.length ){
		callback.call(_this);
	}

	elems.bind('load',function(){
		if (--len <= 0){ callback.call(_this); }
	}).each(function(){
		// cached images don't fire load sometimes, so we reset src.
		if (this.complete || this.complete === undefined){
			var src = this.src;
			// webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
			this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
			this.src = src;
		}
	}); 

	return this;
};

