 $(document).ready(function() {
//So, first, we're going to run Isotope on any pages that would have a bunch of posts
$('.home #posts, .archive #posts, .search-results #posts').isotope({   itemSelector : 'article', animationEngine:'best-available' });
// And, also, on the front page we'll run it for the subfilters.
$('.home #lowerfilters').isotope({   itemSelector : 'ul', animationEngine:'best-available', filter:'.all' });
    $('.home #lowerfilters ul').removeClass('hide');

// Because of media queries that change the layout of the page, Isotope needs to be called when the window is resized.
$(window).resize(function() {
      $("#posts").isotope('reLayout');
});


//Because it's unsightly otherwise, let's fade the articles in after Isotope has been loaded.

$('article').fadeIn();

// Lets do some filtering of article listings
filters = {};



$('.filtering-nav a').click(function(){


    if ( $(this).parents().is('.indexlist') ) {
    $(document).trigger('retrieve.infscr');
       var thisSorter = $(this).attr('rel');
       thisSorter = '.' + thisSorter ; 
       $('#lowerfilters [rel="all"]').click();
       $('#lowerfilters').isotope({ filter: thisSorter });
      
            if ($(this).is('rel=["all"]')){
              $('#posts').isotope({ filter: '*' });
            }
       }



    var $this = $(this),
        isoFilters = [],
        prop, selector;
        
if ($(this).is('.active[rel!="all"]')) {
            var groupAssociation = $(this).data('group');
              filters[ $(this).data('group') ] = '';
              $(this).removeClass('active');
             $(this).closest(".filtering-nav").find('[rel="all"]').click();

} else {

    $(this).closest(".filtering-nav").find('a').removeClass('active');
    $(this).addClass('active');
        filters[ $this.data('group') ] = $this.data('filter');
    }
  
    // store filter value in object
    // i.e. filters.color = 'red'

  for ( prop in filters ) {
    isoFilters.push( filters[ prop ] )
  }
  

  selector = isoFilters.join('');
  $('#posts').isotope({ filter: selector });

// Insert humor, this is what I guess is called an easter egg.
  if (selector == ".meat.dessert"){
  $("#therearenopoststoshow strong").text("There's no such thing as a meat dessert!");
  } else {
    $("#therearenopoststoshow strong").text("No Matches");
  } 
  
  checkifthereareposts();

 
  return false;
});


// This checks to see if there are any posts currently and show a note if there are no posts showing
function checkifthereareposts(){

    var totalarticlecount = $("#posts article").length;
    var totalhiddenarticles = $("#posts article.isotope-hidden").length;

    if ((totalhiddenarticles == totalarticlecount)) {
        $(document).trigger('retrieve.infscr'); //run infinite scroll just cause
        $("#therearenopoststoshow").addClass('rightnow');
    } else {
        $("#therearenopoststoshow").removeClass('rightnow');
    }
}


//smooth jumping for entry icons.

$('.scrollto').click(function(){
var myTarget = $(this).href;
	$.scrollTo( this.hash, 1000);
		return false;
	});
	

$('.entry').each(function(){
if ( $('.entry :nth-child(2)')[0].tagName == "OBJECT" || $('.entry :nth-child(2)')[0].tagName ==  "IFRAME") { $(' .keyimage').remove(); }

	
	
	//$("#comment").charCount({    allowed: 120,    warning: 10,    counterText:'Characters left: '	});

});


// This makes the related posts scroll along if they are not too tall

$('#relatedposts').each(function(){
    $(window).scroll(function(){ 
    var currentwindowHeight = $(this).height();
var currentRelatedPostsHeight = $('#relatedposts').height();
if (currentRelatedPostsHeight < currentwindowHeight) {
    stickifyRelatedPosts();
    } else {
    $('#relatedposts').css({'position': 'relative', 'top': '0px'}); 
    }
    
    });
});



// And this does all the yucky math to figure out whats going on.
function stickifyRelatedPosts(){


var currentEntryHeight = $('.entry').height();
var currentHeaderHeight = $('header').height();
var currentRelatedPostsHeight = $('#relatedposts').height();

var headerminusrelatedposts = currentHeaderHeight - currentRelatedPostsHeight;

var topscrollerBoundary = headerminusrelatedposts + 110;
var storedtopscrollerBoundary =  $('#relatedposts').data('boxheight'); 
if (storedtopscrollerBoundary > topscrollerBoundary) { topscrollerBoundary = storedtopscrollerBoundary }
  //console.log(topscrollerBoundary+','+ $(this).scrollTop());


    $('#relatedposts').height(currentRelatedPostsHeight);
    
      $el = $('#relatedposts'); 
      if ($(window).scrollTop() > topscrollerBoundary && $("#relatedposts").css('position') != 'fixed'){ 
    //  console.log('sticking');
        $('#relatedposts').css({'position': 'fixed', 'top': '20px', 'bottom':'0px'}); 
         $('#relatedposts').data('boxheight', topscrollerBoundary); 
      } else if ( $(window).scrollTop() < topscrollerBoundary && $("#relatedposts").css('position') == 'fixed' ) {
         $('#relatedposts').css({'position': 'relative', 'top': '0px'}); 
     //      console.log('unsticking');
    
    
      }



}



// This turns twitter names into links.

String.prototype.atify = function() { return this.replace(/@[\w]+/g, function(m) { return "<a href='http://www.twitter.com/"+m.replace('@','')+"'>"+m+"</a>"; }); }; 

function replaceURLWithHTMLLinks(text) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(exp,"<a href='$1'>$1</a>"); 
}


// This gets recent tweets

$.getJSON("http://twitter.com/status/user_timeline/windattack.json?count=6&callback=?", function(data){
    $.each(data, function(i, item) {
      //  $("img#profile").attr("src", item.user["profile_image_url"]); 
    $('#themnavtabs div[rel="twitter"]').append('<li>'+ replaceURLWithHTMLLinks(item.text).atify() + '<a target="_blank" href="http://twitter.com/windattack/status/'+ item.id_str+'"><span class="created_at">'+ $.timeago(item.created_at) + '</span></a></li>');    
    });
});

// Lets load some recent images


$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?id=26517701@N04&format=json&count=5&jsoncallback=?', function(data){
  $.each(data.items, function(i,item){
     $("<img class='hide'/>").attr("src", item.media.m).appendTo('#flickrimages').wrap('<a target="_blank" href="' + item.link + '"></a>').fadeIn();;
    if (i > 4) {return false};  
  });
});



// Load those tabs on the side, and when one is selected, adjust the Related Posts stickying function because the tabs are different heights.

$( "#themnavtabs" ).tabs({  selected:0 , fx: { height: 'toggle', duration: 'fast' }, select: function(){ 
$('#relatedposts').data('boxheight',''); 
   stickifyRelatedPosts();

 } });





// Fade out (using CSS) other articles when mousing over one.

$("#posts a article").live({
        mouseenter:function(){
        $('article').not(this).addClass('fader');			
           },
        mouseleave:function(){
                $('article').removeClass('fader');
           }
       }
    );


//Infinte Scrolling!!!!

 $('#posts').infinitescroll({
     navSelector  : "div.navigation",            
    nextSelector : "div.navigation .alignleft a",    
    itemSelector : "a.articlewrap"  ,        
  donetext  : 'No more posts to load.',
    loadingText  : "Loading more posts...",      
        loadingImg : 'http://windattack.com/wp-content/themes/windattackspring2011/images/windattackinfinitescroll.gif',
        debug: false,
        errorCallback: function() { 
          // fade out the error message after 2 seconds
          $('#infscr-loading').animate({opacity: .8},2000).fadeOut('normal');   
          //Tell the NO MATCHES message to remove the part about scrolling to load more pages.
          $('#scrollmoreperhaps').fadeOut();   

        }
        },
        function( newElements ) {
         var selector = $(this).attr('data-filter');
          $('#posts').isotope( 'appended', $( newElements ) ); 
            $('#posts').isotope({ filter: selector });
           checkifthereareposts();
          $('article').fadeIn();
        }, 1000
      );


 });
