jQuery.noConflict();

// The `quickEach` method will pass a non-unique jQuery instance
// to the callback meaning that there will be no need to instantiate
// a fresh jQuery instance on each iteration. Most of the slow-down
// inherent in jQuery's native iterator method (`each`) is the constant
// need to have access to jQuery's methods, and so most developers
// see constructing multiple instances as no issue... E.g.
//     $(...).each(function(){ $(this)... $(this)... $(this)... });
// A better approach would be `quickEach`.
// https://gist.github.com/500145
jQuery.fn.quickEach = (function(){
    var jq = jQuery([1]);
    return function(c) {
        var i = -1, el, len = this.length;
        try {
            while (
                 ++i < len &&
                 (el = jq[0] = this[i]) &&
                 c.call(jq, i, el) !== false
            );
        } catch(e){
            delete jq[0];
            throw e;
        }
        delete jq[0];
        return this;
    };
}());

//borrowed from jQuery easing plugin
//http://gsgd.co.uk/sandbox/jquery.easing.php
jQuery.easing.easeInOutBack = function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
};
jQuery.easing.easeInOutCubic = function (x, t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t*t + b;
	return c/2*((t-=2)*t*t + 2) + b;
};
jQuery.easing.easeInOutBack = function (x, t, b, c, d, s) {
	if (s == undefined) s = 1.70158; 
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
};
jQuery.easing.easeInOutQuad = function (x, t, b, c, d) {
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
};

(function($){
	
	var sidebarWidth = $('#sidebar').width() + parseInt($('#sidebar').css('marginRight'));
	var didScroll = false;
	var slider_max_height = 550;
	
	if($('#spread').length != 0){
		var slideNavOffset = $('#spread').offset().top - 15;
	} else {
		var slideNavOffset = 15;
	}
	
	/* Remove right margins */
	$('#sidebar nav li:nth-child(2n), .simple-ads:nth-child(2n)').addClass('last');
	
	/* Tweets List */
	if($('.tweets-box').attr('data-twitter-replies') != 'false'){
		var tweetReplies = true;
	} else{
		var tweetReplies = false
	}
	$('.tweets-box').tweetable({
		limit: $('.tweets-box').attr('data-twitter-num'),
		username: $('.tweets-box').attr('data-twitter-user'),
		replies: tweetReplies
	});
	
	/* Tipsy */
	$('.tipsy-value').tipsy({
		title: function() { return this.getAttribute('data-tooltip'); },
		gravity: 'e'
	});
	
	/* Slider Init */
	$('.slider').slides({
		play: 4500,
		pause: 2500,
		hoverPause: true,
		effect: 'fade',
		generatePagination: false
	});
	
	/* Vertically center all images in the slider */
	$('.slides_container').quickEach(function(){
		var container = this.height();
		$('img', this).each(function(){
			var img = $(this).height();	
			if(img != $('.slides_container').height()){
				var margin = (container - img)/2; 
				$(this).css('margin-top', margin);
			}
		});
	});
	
	/*
		If a post has a [gallery], we want to add a rel="post-##" to it so
		that all posts open and can be viewed in the same lightbox.
		We also addClass('colorbox') to enable the lightbox on the gallery thumbs.
	*/
	$('.gallery').quickEach(function(){
		
		var postID = this.parent().parent('article').attr('id');
		var $url = $('a', this).attr('href');
		
		if($url.substring($url.length - 1) != '/'){ // make sure that it isn't linking to a page
			$('a', this).addClass('colorbox').attr('rel', postID);
		}
	});
	
	/* Colorbox */
	$('.colorbox').colorbox({
		maxWidth: '90%',
		maxHeight: '90%',
		transition: 'fade'
	})
	
	/* Vertically center the info block content */
	$('.gallery-desc').quickEach(function(){
		var desc_height = this.height();
		if(desc_height != this.parent().height()){
			var margin = (this.parent().height() - desc_height)/2; 
			$(this).css('margin-top', margin);
		}
	});
	
	/* Dropdown Menus */
	$('#site-nav li').hover(function(){
		$('ul:first', this).fadeIn('fast');
	}, function(){
		$('ul:first', this).delay(300).fadeOut('fast');
	});
	
	/* ***************************************
				Horiontal Scrolling
	*************************************** */
	
	// Don't test if it's a iPhone/iPad
	var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    
    if(!agentID){
		$(window).scroll(function() {
		    didScroll = true;
		});
		
		$(window).resize(function() {
			didScroll = true;
		});
		
		setInterval(function() {
	    	if ( didScroll ) {
		        didScroll = false;
		        
		        // Prev link
		        if($(window).scrollLeft() >= $('#sidebar').width()){
					$('#slide-prev').fadeIn();
				} else {
					$('#slide-prev').fadeOut();
				}
				
				// Next link
				if($(window).scrollLeft() <= ($('.infinite').width() - $(window).width() + 10)){
					$('#slide-next').fadeIn();
				} else{
					$('#slide-next').fadeOut();
				}
				
				// Vertical scroll
				if($(window).scrollTop() != 0){
					$('#slide-next, #slide-prev').animate({top: -($(window).scrollTop() - slideNavOffset)});
				} else{
					$('#slide-next, #slide-prev').animate({top: slideNavOffset});
				}
		    }
		}, 800);
	} // end: iPad test
	
	$(window).load(function(){
		
		// Vertically center all images in the slider
		$('.block img').quickEach(function(){
			var img_height = this.height();	
			if(img_height != slider_max_height){
				var margin = (slider_max_height - img_height)/2; 
				this.css('margin-top', margin);
			}
		});
		
		var scrollOffest = 50,
			positions = [],
			paneWidth = 0, // total width of the scroller
			collection = $('.block');
		
		collection.quickEach(function() {
	        positions.push(parseInt(this.offset()['left']));
	        paneWidth += this.width() + parseInt(this.css('marginRight'));
	    });
	    
	    // Resize the window to be as wide as necessary to fit all in one row
	    windowWidth = paneWidth + sidebarWidth;
	    $('.infinite').css('width', windowWidth);
		
		/* Test if the next arrow should be shown when the page is first loaded */
		if($(window).scrollLeft() > ($('.infinite').width() - $(window).width() + 10)){
			$('#slide-next').hide();
		}
		
	 	// Next/Prev Links
	    $("#slide-next, #slide-prev").css('top', slideNavOffset).click(function() {        
	        return scroll($(this).attr('id'));        
	    });
	    
	    // Left/Right Keyboard Arrows
	    $(document).keydown(function(e){
		    switch(e.keyCode){
		    	case 37:
		    		return scroll('slide-prev');
		    		break;
		    	case 39:
		    		return scroll('slide-next');
		    		break;
		    }
		});
		
		function scroll(direction) {
	 
	        var scroll, i,
	            here = ($(window).scrollLeft()+scrollOffest);
	            
	        for(i = 0; i < positions.length; i++) {
	            if (direction == 'slide-next' && positions[i] > here) { scroll = collection.get(i); break; }
	            if (direction == 'slide-prev' && i >= 0 && positions[i] >= here) { 
	            	scroll = collection.get(i-1); 
	            	if(i==0 || i == 1){
	            		i = 'first';
	            	}
	            	break; 
	            }
	        }
	        
	        if (scroll && i != 'first') {
	            $.scrollTo(scroll, {
	            	duration: 500,
	                offset: -scrollOffest,
	                easing: 'easeInOutQuad'
	            });
	        } else if(i == 'first'){
	        	$.scrollTo('0%', {
	                duration: 650,
	                easing: 'easeInOutQuad'
	            });
	        }
	        
	        return false;
	    }

	}); // #window load
	
})(jQuery);
