var console;
if (console == undefined) {
    console = {log: function () {}};
}

function init() {	
	$('body').append('<div id="credit"><a href="http://prologuetheme.tumblr.com">Prologue Theme</a> by <a href="http://blog.haydenhunter.me">Hayden Hunter</a></div>');
			
	if ($('body').hasClass('two')) {
		two_col = true;
	} else {
		two_col = false;
	}
	
	// Pagination offset
	if ($('#pagination').length > 0) {
		pagination_offset = $('#pagination').offset().top - 1;
		pagination_height = $('#pagination').height() + (parseInt($('#pagination').css('padding-top')) * 2);
	}
	
	// Aside offset
	aside_offset = $('#header').outerHeight() + parseInt($('#wrapper').css('padding-top'));
	
	$('#page_top').click(function() {		
		var distance = $(scroll_element).scrollTop() / 2;
		if (distance > 1000){
			distance = 1000;
		}
		$(scroll_element).animate({scrollTop: 0}, distance);		
		return false;
	});
		
	jQuery.easing.def = 'easeOutExpo';
	next_page_url = $('#page_next').attr('href');
	current_page = parseInt($('#page_current').text());
	start_page = parseInt($('#content').attr('title'));
	total_pages = parseInt($('#page_total').text());
	loading = false;
	header_height = $('#header').height();
	$('#header').height(header_height);
	
	pageLocation(start_page);
	asideList();
}

function scrollElement(){
	// http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html
  scroll_element = 'html, body';
  $('html, body').each(function () {
		var init_scroll_top = $(this).attr('scrollTop');
		$(this).attr('scrollTop', init_scroll_top + 1);
		if ($(this).attr('scrollTop') == init_scroll_top + 1) {
			scroll_element = this.nodeName.toLowerCase();
			$(this).attr('scrollTop', init_scroll_top);
				return false;
      }
  });
}

function posts() {
	$('.post').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);
	
	// Adapted from Matthew Buchanan's note filtering
	$("a.dsq-comment-count").each(function() {
			var comment_string = $(this).html().substring(0,$(this).html().indexOf(" "));
			var comment_count = parseInt(comment_string);
			if (comment_count > 0){
				$(this).parent().addClass('active');
			}
		});
		
	fixYoutube();
	fixVimeo();	
	photos();
	blockquoteImages();
}

function searchForm() {	
	$('#search').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);
	
	$('#search_field').focus(function(){
		$(this).parent().parent().addClass('focus');
		if ($(this).val() == 'Search') {
			$(this).val('');
		}
	})
	$('#search_field').blur(function(){
		$(this).parent().parent().removeClass('focus');
		if ($(this).val() == '') {
			$(this).val('Search');
		}
	})
}


// Matthew Buchanan's Improving The YouTube Player
// http://matthewbuchanan.name/post/261951286/improving-the-youtube-player
function fixYoutube() {
	$("div.post object:not(.fixed)").each(function() {
		if ($(this).find("param[value^='http://www.youtube.com']").length > 0) {
			var parent = $(this).parent();
			var youtubeCode = parent.html();
			var params = "";
			if (youtubeCode.toLowerCase().indexOf("<param") == -1) {
				$("param", this).each(function() {
					params += $(this).get(0).outerHTML;
				});
			}
			var oldOpts = /rel=0/g;
			var newOpts = "rel=0&amp;hd=1&amp;color1=0xFFFFFF&amp;color2=0xFFFFFF";
			youtubeCode = youtubeCode.replace(oldOpts, newOpts);
			if (params != "") {
				params = params.replace(oldOpts, newOpts);
				youtubeCode = youtubeCode.replace(/<embed/i, params + "<embed");
			}
			parent.html(youtubeCode);
			
			// Kludgey mods below
			var ytParam = $(this).find('param[name=movie]').attr('value');
			var ytID = ytParam.match(/v\/([0-9A-Za-z-_]*)/);
			
			$.getJSON("http://gdata.youtube.com/feeds/api/videos/"+ytID[1]+"?v=2&alt=json-in-script&callback=?",
				function(data){					
					if(data.entry.media$group.yt$aspectRatio != null){
						parent.find("object, embed").height((parent.find("object").width() * 0.5625)+25);
					} else {
						parent.find("object, embed").height((parent.find("object").width() * 0.75)+25);
					}
			});
		
			parent.find('object').addClass('fixed');		
		}
	});
}

// Matthew Buchanan's Better Vimeo embeds on Tumblr
// http://matthewbuchanan.name/post/261951286/improving-the-youtube-player
function fixVimeo() {
	$("object:not(.fixed)[data^='http://vimeo.com']").each(function() {
	    var parent = $(this).parent();
	    var vimeoCode = parent.html();
	    var params = "";
	    if (vimeoCode.toLowerCase().indexOf("<param") == -1) {
	        $("param", this).each(function() {
	            params += $(this).get(0).outerHTML;
	        });
	    }
	    var oldOpts = /show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=00ADEF/g;
	    var newOpts = "show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=FFFFFF";
	    vimeoCode = vimeoCode.replace(oldOpts, newOpts);
	    if (params != "") {
	        params = params.replace(oldOpts, newOpts);
	        vimeoCode = vimeoCode.replace(/<embed/i, params + "<embed");
	    }
	    parent.html(vimeoCode);
	
			parent.find('object').addClass('fixed');
	});
}

function photos() {
	image_border = '<span class="bdr t"></span><span class="bdr r"></span><span class="bdr b"></span><span class="bdr l"></span>'	
	
	$('.photo .media:not(.fixed)').each(function() {
		// Only perform function on images with high res versions available
		if ($('.high_res', this).attr('title') == $('a', this).attr('href')) {
			
			// Only perform function when image loaded or loaded from cache		
			if ($('img', this)[0].complete){
				// Just loaded
				highRes(this);
			} else {
				// Loaded before js ready
				$('img', this).load(function() {
					// *sigh* scope change
					highRes($(this).parentsUntil('.photo').find('.media'));
				})
			}			
		}
				
		$(this).addClass('fixed');
	})
}

function highRes(target) {
	$('a', target).width($('img', target).width());
	$('.high_res', target).css('display', 'block');
	// $('a', target).append(image_border);
	// $('a .bdr', target).css({'opacity': 0.05})
	// $('a .l, .media a .r', target).height($('img', target).height()-1);
	// $('a .t, .media a .b', target).width($('img', target).width()-1);
}

function blockquoteImages() {
	$('.content:not(.fixed) blockquote img').each(function(){
		var num_parents = 0;
		var img_parents = $(this).parentsUntil('.content');
		var i = 0;
		for (i = 0; i <= img_parents.length-1; i++) {
			if (img_parents[i].nodeName.toLowerCase() == 'blockquote'){
				num_parents++
			}
		}
		
		$(this).css('max-width', parseInt($(this).css('max-width')) - (num_parents * 30));
		$(this).parentsUntil('.post').find('.content').addClass('fixed');
	});
}

// Window onScroll
function scroll() {
	doc_height = parseInt($(document).height());
	window_height = parseInt($(window).height());
	
	// Pagination
	if ($('#pagination').length > 0) {
		if ($(scroll_element).scrollTop() > pagination_offset) {
			$('#pagination').addClass('fixed');
			$('#content').css({'padding-top':pagination_height})
			$('#page_top').show();
		} else if ($(scroll_element).scrollTop() < pagination_offset) {
			$('#pagination').removeClass('fixed');
			$('#content').css({'padding-top':0})
			$('#page_top').hide();
		}	
	}

	// Title
	if (($(scroll_element).scrollTop() > aside_offset) && ($('#title').css('opacity') == 1) && two_col == true) {
		$('#title').addClass('fixed').css({'top':aside_offset - $('#title').height() - 8});
			$('#title:not(.animated)').addClass('animated').css('opacity',0).animate({
				'opacity': 1
			}, 700);			
	} else if (($(scroll_element).scrollTop() < aside_offset) && ($('#title').hasClass('fixed'))) {
		$('#title').animate({
			'opacity': 0
		}, 50, function() {
			$('#title').removeClass('fixed animated').animate({
				'opacity':1
			}, 350)
		});
	}
	
	// Auto loading
	if ($(scroll_element).scrollTop() > (doc_height - (window_height*2.5))) {
		loadNewPage();
	}
	
	pageUpdate(start_page);
}

// Update page counter
function pageUpdate(i) {
	if ($(scroll_element).scrollTop() > $('#page_'+i).offset().top + $('#page_'+i).height() - (window_height/2)) {
		i++
		pageUpdate(i)
	} else if (i != $('#page_current').text()) {
		// only update text value if it's different
		$('#page_current').text(i);
		
		pageLocation(i);		
	}	
}

function pageLocation(i) {
	// page_location width + padding
	page_location_width = $('#page_location').width();
	page_location_padding = parseInt($('#page_location').css('padding-left'))
	// strip - page_location		
	strip_length = $('#page_strip').width() - page_location_width - page_location_padding;		
	// work out width of 1 page unit
	page_unit = strip_length / (total_pages - 1);
	// set position
	
	$('#page_location').stop().animate({left: page_unit * (i-1) - page_location_padding}, 100);
}

function asideList() {		
	if (two_col != true) {		
		var remainder = 5 - $('#profile_external .link_list li').length % 5;
		if (remainder != 5 && $('#profile_external .link_list li').length > 5){
			var i = 1;
			for (i = 1; i <= remainder; i++) {
				$('#profile_external .link_list').append('<li>&nbsp;</li>')
			}
		}
		$('.link_list li:nth-child(5n+1)').addClass('first');
		$('.link_list li:nth-child(5n+2)').addClass('second');
		$('.link_list li:nth-child(5n+3)').addClass('third');
		$('.link_list li:nth-child(5n+4)').addClass('fourth');
		$('.link_list li:nth-child(5n+5)').addClass('fifth');

	} else {
		var remainder = 2 - $('#profile_external .link_list li').length % 2;
		if (remainder != 2 && $('#profile_external .link_list li').length > 2) {
			$('#profile_external .link_list').append('<li class="spacer">&nbsp;</li>')
		}
		
		$('.link_list li:nth-child(odd)').addClass('odd');
		$('.link_list li:nth-child(even)').addClass('even');
		$('#profile_external .link_list li:not(.spacer)').eq(-1).addClass('end');
		$('#profile_external .link_list li').eq(-2).addClass('end');				
	}
}

// Endless scrolling
function loadNewPage() {
	if (next_page_url != null && loading != true){
		$('#loading_string').show();
		$('#page_next').hide();
		loading = true;
		var next_page = current_page+1;
		
		$.ajax({
			url: next_page_url,
			cache: false,
			dataType: 'html',
			success: function(data){				
				// jQuery 1.4 .html() strips out inline Javascript
				// var content = $(data).find('#page_'+next_page).html();			
				
				// Alternate method	
				var content = data.split('<!-- 23dd13dd814b508f6e967fb40905a486 -->')[1].split('<!-- End 23dd13dd814b508f6e967fb40905a486 -->')[0];
				$(content).unwrap();
				
				$('#page_'+current_page).after('<div id="page_'+next_page+'"></div>');
				$('#page_'+next_page).html(content);
				
				$('#loading_string').hide();
										
				if (next_page < total_pages) {
					next_page_url = $(data).find('#page_next').attr('href');
					$('#page_next').attr('href', next_page_url).show();
				} else {
					next_page_url = null;
					$('#loading').remove();					
				}	
				
				current_page = current_page+1;
				
				loading = false;
				
				// Update posts
				posts();
			}
		});
		
	}
}

$(function() {
	scrollElement();
	init();
	posts();
	searchForm();
	$(window).scroll(function() {
		scroll();
  });
});