var focused = false;
var disqus_identifier = '/index';
var i = 0;
var scroll_lock = false;
var pageTracker;
$(document).ready(function(){
	
	$(window).bind('orientationchange', function(e){
		if(DetectTierIphone()){
			orient();
		}
	});
	if(DetectTierIphone()){
		orient();
	}
	$(window).bind('hashchange', function(e){
		var fragment = window.location.hash.substr(1);
		var possible_id = '#'+fragment.substr(1).replace('/', '-').replace('/', '-');
		if(possible_id != '#' && $(possible_id).length > 0){
			if(typeof(_gat) != 'undefined' && _gat != null ){
				if(pageTracker == null) pageTracker = _gat._getTracker("UA-1243705-1");
				pageTracker._trackPageview(fragment);
			}
			$(possible_id).stream_focus();
		}
		else{
			if(typeof(_gat) != 'undefined' && _gat != null ){
				if(pageTracker == null) pageTracker = _gat._getTracker("UA-1243705-1");
				pageTracker._trackPageview(fragment);
			}
			do_stream_load(fragment, false, {})
		}
	});
	$('article#article .post').live('click', function(){
    	window.location.hash = '/'+$(this).attr('id').replace('-', '/').replace('-', '/');
		return false;
	});
	$('article#article').live('click',function(){
		if(focused && $('article#article .post.focused').length > $('article#article .post').length){
			unfocus();
			return false;
		}
	});
	$('nav#nav a, #logo a, a.work, a.resources, a.about, a.thoughts').live('click', function(){
		window.location.hash = $(this).attr('href');
		return false;
	});
	$('article#article a.stream_more').live('click', function(){
		if(focused){
			unfocus();
		}
		var opts = {};
		var href = $(this).attr('href');
		if($('.stream .post').length > 0){ opts.before = $('.stream .post:last time').attr('datetime'); }
		if(href == null) href = $('a:first', this).attr('href');
		$('article#article .more').remove();
		do_stream_load(href, true, opts);
		scroll_lock = false;
		return false;
	});
	
	// $(document).scroll(function(){
	// 		var total = $(document).height() - $(window).height();
	// 		if  ($(window).scrollTop() == (total) && !scroll_lock){
	// 			setTimeout(function(){$('article#article a.stream_more').click();}, 500);
	// 			scroll_lock = true;
	// 		}
	// 	}); 
	
	
	$('.nojs-hidden').css('display', 'inline-block');
	unlink_headers();
	disqusItUp();
	$('.rside .comments a.count').live('click', function(){
		// Figure disqus identifier and url.
		var d= "http://www.orangesparkleball.com/";
		var dc = d.indexOf("#");
		i = i + 1;
		e = $('.disqus-delayed_load:first', $(this).parent());
		disqus_identifier = $(e).parent().attr('rel');
		if(dc!=-1){d=d.substring(0,dc)}
		disqus_url = d + disqus_identifier;
		disqus_container_id = 'disqus_thread_'+i;
		// Drop in the new disqus thread.
		$(e).replaceWith($('<div/>').attr('id', 'disqus_thread_'+i).addClass('my_disqus_thread'));
		var dsq = $('<script/>').attr('id', 'disqusCommentScript'); 
		dsq.attr('type', 'text/javascript'); 
		dsq.attr('async', true);
   		dsq.attr('src', 'http://orangesparkleball.disqus.com/embed.js');
   		$('head').append(dsq);
		$(this).hide();
		return false;
	});
	$(document).ajaxStart(function(){
		$('.ajax-loader').show();
	}).ajaxStop(function(){
		$('.ajax-loader').hide()
	});	
	$('aside#aside').css('min-height', $('article#article').height());
	$('body').bind('asideLoaded', function(e) {
		var sel = $('body').hasClass('narrow') ? 'article#article .intro' : 'aside#aside';
		jQuery(sel + ' .clientcarousel').show();
		jQuery(sel + ' .clientcarousel').jcarousel({
			wrap: 'both',
			buttonNextHTML: null,
			buttonPrevHTML: null,
			visible: 3,
			auto: 3,
			scroll: 1,
			animation: 1000
		});
	});
	$('body').trigger('asideLoaded');	
	if(window.location.hash.substr(1).match(/^comment/)){
		$('body').hasClass('narrow') ? $('.comments a.count:first').click() : $('aside#aside .comments a.count').click(); 
	}
});
$.fn.stream_focus = function(){
	var new_scroll = 0;
	var current_min_height = parseInt($('aside#aside').css('min-height'));
	var new_pad_top = 0;
	if(focused && $(this).hasClass('focused')){
		unfocus();
	}
	else{
		if(window.location.hash != '#/'+$(this).attr('id').replace('-', '/').replace('-', '/')){
			window.location.hash = '/'+$(this).attr('id').replace('-', '/').replace('-', '/');
	    }
		else{
			unfocus();
	    	$(this).addClass('focused');
			$('.rside .comments a.count', this).show();
			$('.rside .comments a.count.activated', this).show();
	    	focused = true;
			$('#disqus_thread').remove();
	    	$('aside#aside').html(innerShiv($('aside.rside', this).html()));
			$('.nojs-hidden').css('display', 'inline-block');
			$('aside#aside .rside').addClass('focused');
			
			current_min_height = $('article#article').height();
			new_pad_top = $(this).offset().top - $('aside#aside').offset().top - 5;
			$('aside#aside').css('min-height', (current_min_height - new_pad_top));
			$('aside#aside').css('padding-top', new_pad_top);
			
			new_scroll = $(this).offset().top - $('header#header').height() - 20;
			new_scroll = new_scroll > 0 ? new_scroll : 0;
			if(!$('body').hasClass('narrow')){
				if(do_scroll()) $.scrollTo(new_scroll, 800);
			}
			disqusItUp();
		}
		return false;
	}
}

function do_scroll(){
	return !(DetectIpad() || DetectTierIphone());
}
function do_stream_load(url, append, opts){
	if(focused && $('.stream .post.focused').length > 0){
		unfocus();
	}
	if(!append){
		$('.stream').html('&nbsp;');
		$('.intro').remove();
	}
	
	if(do_scroll() && !append) $.scrollTo(0, 800);
	if($('.stream').length == 0) $('article#article').html('<div class="stream">&nbsp;</div>');
	$.get(url, opts, function(data){
		if(append){$('.stream').append(innerShiv(data));}
		else{
			$('.stream').replaceWith(innerShiv(data));
		}
		if($('article#article .intro').length > 0){
			$('aside#aside').empty();
			$('article#article .intro').clone(true).appendTo('aside#aside');
			$('body').trigger('asideLoaded');
		}
		if($('article#article .post').length == 1){
			$('article#article .post').stream_focus();
		}
		$('aside#aside').css('min-height', $('article#article').height());
		unlink_headers();
	}, 'html');
	return false;
}


function unlink_headers(){
	$('.post header h1').each(function(i,e){$(e).html($(e).text())})
}

function unfocus(){
	var focus_offset = $('.post.focused').length > 0 ? $('.post.focused').offset().top : 0;
	$('aside#aside').css('padding-top', 0);
	$('aside#aside .rside').removeClass('focused');
	$('.post').removeClass('focused');
	$('aside#aside').html('');
	$('.rside .my_disqus_thread').remove();
	$('.rside .disqus_comments').each(function(i,e){
		if($('.disqus-delayed_load', $(e)).length == 0)
			$(e).append($('<div class="disqus-delayed_load"/>'));
	});
	$('head script').each(function(i, e){
		if($(e).attr('src') && $(e).attr('src').match(/disqus.com/)) $(e).remove();
	})
	$('aside#aside').css('min-height', $('article#article').height());
	focused = false;
}
var disqus_identifier;
var disqus_shortname = "orangesparkleball";
function disqusItUp(){
	var selector = ($('body').hasClass('narrow') ? '.post.focused .rside' : 'aside#aside');
	$(selector+' .disqus-delayed_load').each(function(i, e){
		// Remove the old thread
		$('#disqusCommentScript').remove();
		$('head script').each(function(i, e){
			if($(e).attr('src') && $(e).attr('src').match(/disqus.com/)) $(e).remove();
		})
		

		var s = document.createElement('script'); s.async = true;
		s.id="disqusCount";
		s.src = 'http://disqus.com/forums/orangesparkleball/count.js';
		(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
		
		
		//$(e).replaceWith($('<iframe/>').addClass('autoHeight').attr('src', '/'+$(e).parent().attr('rel')+'/comments'));
	});
}

// For iPhone orientation.
function orient()
		{
			switch(window.orientation){
					case 0: 
						$('body').addClass('narrow');
						$('head meta[name=viewport]').attr('content', 'width=640');
			        break;
					case -90: 
						$('body').removeClass('narrow');
						$('head meta[name=viewport]').attr('content', 'width=960');
				    break;
					case 90: 
						$('body').removeClass('narrow');
						$('head meta[name=viewport]').attr('content', 'width=960');
					break;
					case 180:
						$('body').addClass('narrow');
						$('head meta[name=viewport]').attr('content', 'width=640');
					default:
						$('body').addClass('narrow');
						$('head meta[name=viewport]').attr('content', 'width=640');
					break;
		}
	}
