var postsPointer = 0;
var postsPerLoad = 10;
var morePosts = true;

function isEven(n){
	return !(n % 2);
}

function oddOrEven(n){
	return isEven(n) ? "even": "odd";
}

function errorToDeath(shit){
	$('div#postsContainer').html('<div class="blogError"><img src="/images/fucked.jpg" /><p>The WNV satellite is experiencing technical difficulties right now. Please wait until cosmic radiation levels decrease and try again.</p></div>');
	$('div#loadingPosts').fadeOut("slow", function(){
		$('div#postsContainer').fadeIn("slow");
	});
}

function parseTumblr(data){
    var postHTML = '';
    var gotten = 0;
    
    $.each(data.posts, function(i, posts){
    								
    	var id = this.id;
        var type = this.type;
        var date = this.date;
    	var url = this.url;
    	
    	//construct strings used to build each post
    	
    	var top = '<li class="post ' + type + '"><a href="' + url + '" class="icon"></a><div class="posted">' + date + '</div>';
    	
    	switch(type){
    		case 'regular':
    			var middle = '<h3 class="title">' + this['regular-title'] + '</h3>';
       			middle += '<div class="caption">' + this["regular-body"] + '</div>';
    			break;
    			
    		case 'conversation':
    			var middle = '<h3 class="title">' + this['conversation-title'] + '</h3>';
    			middle += '<div class="lines">';
    			$.each(this.conversation, function(i, line){
    				middle += '<div class="line ' + oddOrEven(i) + '"><strong>' + this.label + '</strong> ' + this.phrase + '</div>';
    			});
    			middle += '</div>';
    			break;
    			
    		case 'photo':
    			var middle = '<a href="' + this["photo-url-1280"] + '" target="_blank">';
    			middle += '<img src="' + this["photo-url-500"] + '" width="500" /></a>';
    			if(this["photo-caption"])
        			middle += '<div class="caption">' + this["photo-caption"] + '</div>';
    			break;
    			
    		case 'quote':
    			var middle = '<div class="caption">&#147;' + this["quote-text"] + '&#148;</div>'
    			if(this["quote-source"])
        			middle += '<div class="source">- ' + this["quote-source"] + '</div>';
    			break;
    			
    		case 'link':
    			var middle = '<a href="' + this["link-url"] + '" class="postlink" target="_blank">' + this["link-text"] + '</a>';
    			if(this["link-description"])
        			middle += '<div class="caption">' + this["link-description"] + '</div>';
    			break;
    			
    		case 'audio':
    			var middle = '<div class="audio_player">' + this["audio-player"] + '</div>';
    			if(this["audio-caption"])
        			middle += '<div class="caption">' + this["audio-caption"] + '</div>';
    			break;
    			
    		case 'video':
    			var middle = '<div class="vid-wrap">' + this["video-player"] + '</div>';
    			if(this["video-caption"])
        			middle += '<div class="caption">' + this["video-caption"] + '</div>';
    			break;
    			
    		default:
    			var middle = 'This post was damaged during transmission from the WNV satellite. Probably a cosmic ray or something.';
    			break;
    	}
    	
    	var bottom = '<div class="clear">&nbsp;</div></li>';
    	
    	//build the entire li 
    	postHTML += top + middle + bottom;
    	
    	gotten++;
    });//each
    
    //update pointer
    postsPointer += gotten;
    morePosts = (gotten >= postsPerLoad);
    
    return postHTML;
}

function getMorePosts(){
    $('div#loadMore').fadeOut("normal");
 	$('div#loadingPosts').html('<span id="loadingMsg">Attenuating Blog Antenna...</span>');
	$('div#loadingPosts').fadeIn("fast", function(){
		var sendData = {
			"host": "http://comicftw.tumblr.com/",
			"path": "api/read/json/",
			"debug": "1",
			"num": postsPerLoad,
			"start": postsPointer
		};
        
        //replaced by jacked_proxy: handles its own damn config now
        ////just takes host name and url(path), GET and POST vars added automagically to the request

		$("#loadingMsg").fadeOut("normal", function(){
			$("#loadingMsg").html("Beaming Posts From Remote Endpoint...");
			$("#loadingMsg").fadeIn("fast", function(){
				$.ajax({
					type: "GET",
					url: "jacked_proxy.php",
					dataType: "json",
					data: sendData,
					error: function(xhr, msg, except){
						errorToDeath(msg);
					},
					success: function(data, textStatus){
				
						debugConsole(data.posts); 
						
						$("#loadingMsg").fadeOut("normal", function(){
							$("#loadingMsg").html("Propagating Blog Trees...");
							$("#loadingMsg").fadeIn("fast", function(){
								$('div#postsContainer').append('<ol id="posts">');
						      	
						      	posts = parseTumblr(data);
						      	$('div#postsContainer').append(posts);
						      	
						      	$('div#postsContainer').append('</ol>');
						      	
								$("#loadingMsg").fadeOut("normal", function(){
									$("#loadingMsg").html("Reticulating Splines...");
									$("#loadingMsg").fadeIn("fast", function(){
									
										$('div#loadingPosts').fadeOut("slow", function(){
											if(morePosts)
											    $('div#loadMore').fadeIn("slow");
											$('div#postsContainer').fadeIn("slow");
											
										});//loaded
									
									});	//splines in
								});//splines out
							});//propagating in
						});//propagating out
					}//ajax success
				});//ajax
			});//download in
		});//download out
	});//antenna in

}

$(document).ready(function(){

    $('div#loadMore').click(function(e){
        getMorePosts();
    });
    
    $('div#loadMore').hover(function(){
        $(this).animate({ backgroundColor: "#0099FF" });
    }, function(){
        $(this).animate({ backgroundColor: "#333333" });        
    });

    $('div#loadMore').fadeOut("normal");	
	$('div#loadingPosts').html('<span id="loadingMsg">Attenuating Blog Antenna...</span>');
	$('div#loadingPosts').fadeIn("fast", function(){
		var sendData = {
			"host": "http://comicftw.tumblr.com/",
			"path": "api/read/json/",
			"debug": "1",
			"num": postsPerLoad
		};
        
        //replaced by jacked_proxy: handles it's own damn config now
        ////just takes host name and url(path), GET and POST vars added automagically to the request
	
		$("#loadingMsg").fadeOut("normal", function(){
			$("#loadingMsg").html("Beaming Posts From Remote Endpoint...");
			$("#loadingMsg").fadeIn("fast", function(){

				$.ajax({
					type: "GET",
					url: "jacked_proxy.php",
					dataType: "json",
					data: sendData,
					error: function(xhr, msg, except){
						errorToDeath(msg);
					},
					success: function(data, textStatus){
				
						debugConsole(data.posts); 
						
						$("#loadingMsg").fadeOut("normal", function(){
							$("#loadingMsg").html("Propagating Blog Trees...");
							$("#loadingMsg").fadeIn("fast", function(){
								$('div#postsContainer').append('<ol id="posts">');
						      	
						      	posts = parseTumblr(data);
						      	$('div#postsContainer').append(posts);
						      	
						      	$('div#postsContainer').append('</ol>');
						      	
								$("#loadingMsg").fadeOut("normal", function(){
									$("#loadingMsg").html("Reticulating Splines...");
									$("#loadingMsg").fadeIn("fast", function(){
									
										$('div#loadingPosts').fadeOut("slow", function(){
											if(morePosts)
											    $('div#loadMore').fadeIn("slow");
											$('div#postsContainer').fadeIn("slow");
											
										});//loaded
									
									});	//splines in
								});//splines out
							});//propagating in
						});//propagating out
					}//ajax success
				});//ajax
			});//download in
		});//download out
	});//antenna in
	
});//domready
