$(document).ready(function() {
  
  	var postsPerPage = 10;
  	if(thePage > 1){
  	var theStart = (thePage * postsPerPage)-postsPerPage;
	}
	
	var preLoadHTML = $('.blog').html();
	
	theString = 'http://markofthedead.tumblr.com/api/read/json?';
	
    if(thePost != ""){
		theString += '&id=' + thePost;
	}else{    
        if(theStart > 0){
            theString += 'start=' + theStart;
        }
	
        if(theStart > 0){
            theString += '&num=' + postsPerPage;
        }else{
            theString += 'num=' + postsPerPage;
        }

        if(theTag == "junk"){
            //Show All
        }else if(theTag != ""){
            theString += '&tagged=' + theTag;
        }else{
            theString += '&tagged=blog';
        }
	
        if(theType != ""){
            theString += '&type=' + theType;
        }
    }
	
	theString += '&callback=?';
	
	$.getJSON(theString, function(data){
		
//	$.getJSON('http://markofthedead.tumblr.com/api/read/json?tagged=blog&callback=?', function(data){
	
	var totalPosts = data['posts-total'];
	var totalPages = Math.ceil(totalPosts/postsPerPage);
	
	var theBlog = "";
	var theCount = 0;
				
			$.each(data.posts, function(index, item){
			
                theBlog += '<div class="thePost">';
                
				if(item.type == "regular"){
					theBlog += '<h2>' + item["regular-title"] + '</h2><div class="regPost">' + item["regular-body"] + '</div><h5>' + item.date + '</h5>';
				}else if(item.type == "photo"){
					if(item.photos.length > 0){
						$.each(item.photos, function(index, photo){
							if(index == 0){
								theBlog += '<a href="' + item["photo-url-500"] + '" class="popupImg firstImg" rel="group' + item.id + '"><img src="' + item["photo-url-500"] + '" alt="" width="540" /></a>';
							}else{
								theBlog += '<a href="' + photo["photo-url-500"] + '" class="popupImg" rel="group' + item.id + '"><img src="' + photo["photo-url-100"] + '" class="img100" alt=""/></a>';
							}
						})
						theBlog += '<h5>' + item.date + '</h5>';
					}else{
						if(item["photo-link-url"]){
							theBlog += '<div class="photoholder"><a href="' + item["photo-link-url"] + '" class="iframe popupLink"><img src="' + item["photo-url-500"] + '" alt="" /></a></div><p>' + item["photo-caption"] + '</p><h5>' + item.date + '</h5>';
						}else{
							theBlog += '<div class="photoholder"><a href="' + item["photo-url-500"] + '" class="popupImg"><img src="' + item["photo-url-500"] + '" alt="" /></a></div><p>' + item["photo-caption"] + '</p><h5>' + item.date + '</h5>';
						}
					}
				}else if(item.type == "quote"){
					//QUOTE
					theBlog += '<p class="quotation">"' + item["quote-text"] + '"</p><p class="quotesource"> - ' + item["quote-source"] + '</p>' + '<h5>' + item.date + '</h5>' ;
				}else if(item.type == "link"){
					//link
					theBlog += '<h2>Link;</h2><p><a href="' + item["link-url"] + '">' + item["link-text"] + '</a></p>';
				}else if(item.type == "conversation"){
					//chat
					theBlog += '<h2>' + item["conversation-title"] + '</h2><ul class="conversation">';
					var theConvo = "";
					var classArr = new Array();
					$.each(item.conversation, function(index, line){ //for each 'line' in 'conversation'
						if($.inArray(line.name, classArr) == -1){ //if 'name' not in array, add it.
							classArr.push(line.name);
						}
					});
					
					$.each(item.conversation, function(index, line){ 			//for each 'line' in 'conversation'
						var theClass = "convoParty"; 							//create class convoParty
						theClass += $.inArray(line.name, classArr); 			//add number for each unique 'name' in conversation.
						theConvo += '<li class="' + theClass + '"><strong>' + line.label + '</strong> ' + line.phrase + '</li>';
					});
					
					
					theBlog += theConvo + '<li class="chatDate">' + item.date + '</h5></ul>';
					//console.debug(classArr);
				}else if(item.type == "audio"){
					//audio
					theBlog += '<div class="audio_player"><p class="theArtist">' + item["id3-artist"] + ' - ' + item["id3-title"] + '</p>' + item["audio-player"] + '</div>' + item["audio-caption"];
				}else if(item.type == "video"){
					//video
					theBlog += item["video-player"] + item["video-caption"] + '<h5>' + item.date + '</h5>';			
				}else{
					//FUCK. something broke.
					}

			
			if(item.tags != undefined){
                theBlog += '<ul class="tagList">';
				$.each(item.tags, function(index, theTag){
					theBlog += '<li><a href="/?tagged='+ theTag +'">'+ theTag +'</a></li>';
				});
				theBlog += '</ul><br style="clear:both;"/>';
            };
            
            
            theBlog += "</div>";
            //theBlog += "<hr/>";
			

			theCount ++;
				
			});
			
            if(thePost != ""){
                //no page Nav
            }else{
                var theNav = "<ul class=\"pageNav\">";
                
                if(thePage<10 | totalPages<20){
                    var startPoint = 1;
                    var endPoint = 20;
                }else{
                    var startPoint = thePage - 10;
                    var endPoint = thePage + 10;
                }
                
                for(j=startPoint;j<=totalPages && j<endPoint;j++){
                    if(j==thePage){
                        theNav += '<li class=\"currentPage\">' + j + '</li> ';
                    }else{
                        theNav += '<li><a href="?tagged=' + theTag + '&page=' + j + '">' + j + '</a></li> ';
                    }
                }
			
                theNav += "</ul>";
			
                theBlog += theNav;
			}
            
			$('.blog').html('');		
			$('.blog').append(theBlog);
			$('.blog hr:last').remove();
			$('object').attr('width','560');
			$('object embed').attr('width','560');
			$("a.popupImg").fancybox();
			$("a.popupLink").fancybox({
				'width'				: '85%',
				'height'			: '80%',
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe'
			});
			
	
	})
//	.success(function() { alert("success"); })
//	.error(function() { alert("error"); })
//	.complete(function() { alert("complete"); });


window.onload = function()
{
  
	if( $('.blog').html() == preLoadHTML){
	  $('.blog').html('<p>Whoops! An error occured. Unable to load posts - server may be down. Please try again shortly.</p>');
	}
  
};



});

//------------------------- KONAMI CODE ------------------------------------

$(document).ready(function(){
				$(window).konami(function(){
					alert('sorry, no Konami features yet.');
				});
			});

// --------------------------------------------------------------------------


// -----------------------TWEETS-------------------------------------

$(document).ready(function() {
	
	var theUsername = "oftheweb"; // GET THIS USERS TWEETS


	$.getJSON('http://twitter.com/status/user_timeline/' + theUsername + '.json?count=21&callback=?', function(data){
        $.each(data, function(index, item){
                if(!item.in_reply_to_screen_name){ // ONLY RETURN ORIGINAL TWEETS
					var theDate = item.created_at.split(" ");
					var dateOut = theDate[3] + ' - ' + theDate[0] + ' ' + theDate[1] + ' ' + theDate[2] + ' ' + theDate[5];
					$('#theTweets').append('<li class="tweet"><p>' + item.text.linkify() + '</p><p class="datestamp">' + dateOut + '</p></li>');
				}
        });
	});

	


	

});

// --------------------------------------------------------------------------





// -------------------------------------- LINKIFY ------------------------------------

String.prototype.linkify = function() {
        return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
                return m.link(m);
        });
};

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  var r = '';
  if (delta < 60) {
        r = 'a minute ago';
  } else if(delta < 120) {
        r = 'couple of minutes ago';
  } else if(delta < (45*60)) {
        r = (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (90*60)) {
        r = 'an hour ago';
  } else if(delta < (24*60*60)) {
        r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
        r = '1 day ago';
  } else {
        r = (parseInt(delta / 86400)).toString() + ' days ago';
  }
  
};

// --------------------------------------------------------------------------
