
var colWidth = 326;
var request_sent = false;

$(function() {

	var location = String(window.location);
	if(location.indexOf('?m=') != -1) {
		$('#archives option').each(function() {
			if($(this).attr('value') == location) {
				$(this).attr('selected','selected');
				$('#container').after($('<div class="next-prev-links"></div>'));
				if($(this).next().text() != $('#archives option:first').text()) {
					var prevLink = $('<div class="prev-post-link"><a href="'+ $(this).next().attr('value') +'">'+ $(this).next().text() +'</a></div>');	
					$('.next-prev-links').append(prevLink);
				}				
				if($(this).prev().text() != $('#archives option:first').text()) {
					var nextLink = $('<div class="next-post-link"><a href="'+ $(this).prev().attr('value') +'">'+ $(this).prev().text() +'</a></div>');				
					$('.next-prev-links').append(nextLink);
				}
			}
		});		
	}

	//setWidth();
	$('#container').masonry({ columnWidth: colWidth });
	
	$('#header select').sSelect({ddMaxHeight : '400'});
	$('.newList').mouseover(function() {$(this).children('li.hiLite').removeClass('hiLite');});
	$('#categories .newList li').click(function() {
		var index = jQuery.inArray(this, $(this).parent().children());
		var cat_id = $('#categories select option')[index].value;
		if(cat_id <= 0)
		self.location = String(self.location).split('?')[0];
		else
		self.location = '?cat=' + cat_id;					
	});
	$('#archives .newList li').click(function() {
		var index = jQuery.inArray(this, $(this).parent().children());
		var url = $('#archives select option')[index].value;
		if(url <= 0)
		self.location = String(self.location).split('?')[0];
		else
		self.location = url;					
	});
	$('#bookmarks .newList li').click(function() {
		var index = jQuery.inArray(this, $(this).parent().children());
		var url = $('#bookmarks select option')[index].value;
		if(url <= 0)
			return;
		else
		window.open(url);					
	});	
	
});

function lastPostFunc() { 
	var prev_url = $('.prev-posts:first').children().attr('href');
	if(!prev_url) return;
	if(request_sent) return;
	request_sent = true;
	//$('body').append('<div class="loading"></div>');
	$.post(prev_url, function(data) {
		if (data != "") {
			$(".post:last").after(data);	
			$('#container').masonry({ columnWidth: colWidth });
			//$('.loading').remove();
			request_sent = false;
		}
	});
} 
	
function setWidth() {
	var w = $(window).width();
	if (w < 1024) w = 978;
	$('#container, .next-prev-links').css({width: colWidth * Math.floor(w / colWidth)});
}

$(window).scroll(function(){
	if  ($(window).scrollTop() > $(document).height() - $(window).height() * 3){
	   lastPostFunc();
	}
});


//$(window).resize(function() { setWidth(); });



