/* ---------------------------------- */

/* TFAL Plugins */

/*
 * AUTHOR
 * Ian Coyle
 * @link http://www.iancoyle.com
 *
 *
 * TABLE OF CONTENTS
 *
 * @TFAL:TouchEnable
 * @TFAL:OrientEnable
 * @TFAL:iPhoneNav
 * @TFAL:Post
 * @TFAL:PhotoGallery
 * @TFAL:Filters
 * @TFAL:Delicious
 * @TFAL:Quote
 * @TFAL:Keyboard
 * @TFAL:Covers
 * @TFAL:Links
 *
 */


/* ---------------------------------- */

/* TouchEnable */

(function($) {

   $.fn.TouchEnable = function(settings) {
   
    var defaults = {
			threshold: {
				x: 30,
				y: 50
			},
			swipeLeft: function() { $(document).triggerHandler('KEYBOARD_RIGHT')}, 
			swipeRight: function() { $(document).triggerHandler('KEYBOARD_LEFT') },
			swiping: function(x) { $(document).triggerHandler('SWIPING',-x);} 
		};
		
		var options = $.extend(defaults, options);
		
		if (!this) return false;
		
		return this.each(function() {
			
			var me = $(this),
			    $self = $(this),
			    originalCoord = { x: 0, y: 0 },
			    finalCoord = { x: 0, y: 0 };
			
			function touch_start(event) {
				
				console.log('Starting swipe gesture...')
				
				originalCoord.x = event.targetTouches[0].pageX
				
				originalCoord.y = event.targetTouches[0].pageY
				
				$(document).triggerHandler('SWIPE_START',originalCoord.x)
				
			}
			
			function touch_move(event) {
			  	
				finalCoord.x = event.targetTouches[0].pageX // Updated X,Y coordinates
				
				finalCoord.y = event.targetTouches[0].pageY
				
			}

			function touch_end(event) {
			
				changeY = originalCoord.y - finalCoord.y
				
				changeX = originalCoord.x - finalCoord.x
							
				if(changeY < defaults.threshold.y && changeY > (defaults.threshold.y*-1)) {
					
					changeX = originalCoord.x - finalCoord.x
				
					if(changeX > defaults.threshold.x) {
						defaults.swipeLeft()
					}
			
					if(changeX < (defaults.threshold.x*-1)) {
						defaults.swipeRight()
			
					}
				
				}
								
				$(document).triggerHandler('SWIPE_END');
				
			}
			
			function touch_cancel(event) { 


			}
			
			this.addEventListener("touchstart", touch_start, false);
			this.addEventListener("touchmove", touch_move, false);
			this.addEventListener("touchend", touch_end, false);
			this.addEventListener("touchcancel", touch_cancel, false);
			
		});

  }
   
})(jQuery);


/* ---------------------------------- */

/* Orientation */

(function($) {

   $.fn.OrientEnable = function(settings) {
   
    var config    = {},
        $body     = $('body'),
        _rotation = null;
 
    if (settings) $.extend(config, settings);
  
      this.each(function() {
      
        var $self     = $(this);
        
        setInterval(orientation_check,250);
        
        function orientation_check(e) {
        
          if(_rotation != window.orientation)
		        orientation_set();
        }
        
        function orientation_set() {
        

          switch(window.orientation){

            case 0:

              orient = 'portrait';
              $body.removeClass('landscape').addClass(orient);
              
            break;
          
            case 90:
            
              orient = 'landscape';
              $body.removeClass('portrait').addClass(orient);
              
            break;
            
            case -90:
            
              orient = 'landscape';
              $body.removeClass('portrait').addClass(orient);
              
            break;
        
          }
          
          _rotation = window.orientation;
          
          setTimeout(scrollTo,0,0,1);
        
        }
      
      });
   
   }
   
})(jQuery);


/* ---------------------------------- */

/* IPHONENAV */

(function($) {

   $.fn.iPhoneNav = function(settings) {
   
    var config    = {},
        $body     = $('body');
 
    if (settings) $.extend(config, settings);
  
      this.each(function() {
      
        var $self     = $(this),
            $a        = $self.find('li:first-child a'),
            _active   = false;
        
        $self
        .bind('click',on_click);
        
        $a
        .bind('click',on_a_click);
        
                
        function on_click(e) {
        
          var h = _active ? 50 : 100;
          
          $self.stop().animate({height: h},650,'easeInOutQuart');
          
          _active = !_active;
        
        }
      
        function on_a_click(e) {
          
          e.preventDefault();
        
        }
        
              
      });
   
   }
   
})(jQuery);


/* ---------------------------------- */

/* NAV */

(function($) {

   $.fn.TFALNav = function(settings) {

 
    if (settings) $.extend(config, settings);
  
      this.each(function() {
      
        var $self   = $(this),
            $navs   = $self.find('a'),
            _iphone = ((navigator.userAgent.match(/Android/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
        
        $(document)
        .bind('KEYBOARD_KEY',on_keyboard_key)
        .bind('click',on_click);
        
        function on_keyboard_key(e,id) {
        
          $navs.each(function(){
          
            if ($(this).attr('rev')==id)
              location.href = $(this).attr('href');
          
          });
          
        
        }
        
        function on_click(e){
        
          
        }
        
        
        
      });
   
   }
   
})(jQuery);



/* ---------------------------------- */

/* POST */

(function($) {

   $.TFALPost = {
      
      version: '1.0.9',
      mobile:  false,
      tablet: false
      
   };
   
   $.fn.TFALPost = function(settings) {
     
     var config = {},
        $body            = $('body'),
        $html            = ($.browser.mozilla || $.browser.msie) ? $('html') : $body,
        $wrapper         = $('#wrapper'),
        _sadBrowser      = $.browser.opera || ($.browser.msie && $.browser.version.indexOf('7.')>-1),
        _iphone          = ((navigator.userAgent.match(/Android/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
    
     if (settings) $.extend(config, settings);
     
  
     this.each(function() { 
 
          var $self            = $(this),
              $article_content = $self.find('.post-content'),
            	 _column_width    = config.COLUMN_WIDTH ? config.COLUMN_WIDTH : 320,
              _speed           = config.SPEED ? config.SPEED : 650,
              _ease            = config.EASE ? config.EASE : 'easeInOutQuart',
              _loadingnext     = false,
              _shift           = false,
              _pagewidth       = $body.hasClass('category-cover') || $body.hasClass('home') ? 3 : 1,
              _is_feature      = $wrapper.hasClass('site-features'),
              _swipe_offset    = 0,
              active_col       = 0,
              active_row       = 0,
              total_col        = $self.find('.page').length-1;


	//TO DO
	//colocar na largura da div post-content a soma da largura de todas as imagens
	//_column_width = post-content.width() / total_col
	
			
			
				/*$('.page').each(function(index) {
  			  //alert(index + ': ' + $(this).width());
			  	_divsW += $(this).width();
			  //alert(_divsW);
		 		 });
  				_column_width = _divsW/total_col
				alert(_column_width);*/
			
			
          if (config.WRAPPER)
		  
		  
            config.WRAPPER.css({overflowX: 'hidden'}); 
        

          
          if (_is_feature && !$body.hasClass('home')) 
            total_col+=2;
          
          
          $.TFALPost.self = $self;  
            
          $self
          .TFALPostNav();
          
          $body
          .bind('FILTER_OUT',on_filter_out)
          .bind('FILTER_APPLY',on_filter_apply)
                    
          $(document)
          .bind('KEYBOARD_RIGHT',on_key_right)
          .bind('KEYBOARD_LEFT',on_key_left)
          .bind('KEYBOARD_UP',on_key_up)
          .bind('KEYBOARD_DOWN',on_key_down)
          .bind('KEYBOARD_SHIFT',on_shift)
          .bind('KEYBOARD_RELEASE',on_key_release)
          .bind('SWIPE_START',on_swipe_start)
          .bind('SWIPING',on_swiping);
          
          $self
          .bind('NEXT',on_key_right)
          .bind('PREV',on_key_left);
          
          setTimeout(init_view,1);
          
          function init_view(){
          
            seek();
          
          } 
          
          function seek(position) {
          
            // Ha. The only comment you'll see.
            // Opera & IE7 Don't work using scrollLeft to animate, instead use marginLeft
            // In case you're wondering, scrollLeft is waaay more efficient & smoother animation than marginLeft and left
            
            if (_sadBrowser)
              $article_content.stop().animate({marginLeft:-_column_width*_pagewidth*active_col},_speed,_ease);
            else
              $self.stop().animate({scrollLeft:_column_width*_pagewidth*active_col},_speed,_ease);
          
          }
          
          function on_swipe_start() {
          
            _swipe_offset = $self.attr('scrollLeft')
          
          }
          
          function on_swiping(e,x) {
          
            $self.attr('scrollLeft', _swipe_offset + x)
          
          }
          
          function on_key_release(e) {
          
            _shift = false;
          
          }
          
          function on_shift(e) {
          
            _shift = true
          
          }
          
          function on_key_right(e) {
          

            if ($body.hasClass('home')) {
            
              active_col++;
              
              if (active_col>total_col)
                active_col = total_col; 
              
              $body.triggerHandler('COVER',active_col)
              
              seek();
              
              return;
            
            }
            
            if ($body.hasClass('category-shelf') ) {
            
              if ($.TFALPost.tablet)
                return;
                
              active_row++
              
              var hght = ($.TFALPost.mobile) ? 300 : 550;
                
              $html.stop().animate({scrollTop:hght*active_row},_speed,_ease);
            
              return;
            
            }
            
            if (_shift==true)
              active_col+=4;
            else
              active_col++;
            
            if (active_col>total_col-2 && !_loadingnext) {
              load_next();
              
            }
            
            if (_is_feature && active_col>total_col-1) {
                
                var current_article_id = $('a.permalink').attr('rel');
                
                $('body').triggerHandler('ARROW_NEXT',current_article_id);
              
            }
              
                
            if (active_col>total_col)
              active_col = total_col;
              
            seek();
            
          }
          
          function on_key_left(e) {
          
          
            if ($body.hasClass('home')) {
            
              active_col--;
              
              if (active_col<0)
                active_col = 0;
              
              $body.triggerHandler('COVER',active_col)
              
              seek();
              
            
              return;
            
            }
            
            if ($body.hasClass('category-shelf')) {
            
              active_row--;
              
              if (active_row<0)
                active_row = 0;
              
              $html.stop().animate({scrollTop:600*active_row},_speed,_ease);
            
              return;
            
            }
            
            
            if (_shift==true)
              active_col-=4
            else
              active_col--;

            
            if (active_col<0) {
              
              if (_is_feature) {
                
                var current_article_id = $('a.permalink').attr('rel');
                
                $('body').triggerHandler('ARROW_PREV',current_article_id);
              
              }
            
              active_col = 0;
              
              
            }
            
            seek();
            
          }
          
          function on_key_up(e) {
          
              active_row--;
              
              if (active_row<0)
                active_row = 0;
              
              e.preventDefault();
              
              $html.stop().animate({scrollTop:600*active_row},_speed,_ease);
            
                        
            
          }
          
          function on_key_down(e) {
          
              active_row++
              
              e.preventDefault();
              
              $html.stop().animate({scrollTop:600*active_row},_speed,_ease);
            
              
            
          }
          
          function on_filter_out() {
          
            active_col = 0; 
          
            $article_content.css({marginLeft:0});
          }
          
          function load_next() {
            
            if ($wrapper.hasClass('site-curated') && !$body.hasClass('single'))
              $body.triggerHandler('APPEND',(total_col+1));
            else
              return;
              
            _loadingnext = true;

          
          }
          
          function on_filter_apply(e,append) {
          
            total_col = $self.find('.page').length-1;
            
            _loadingnext = false;
            
            if (!append)
              $self.animate({'scrollLeft':0},1);
            
            $("a[rel^='prettyPhoto']").prettyPhotoLink();
            
            $("a._blank").TFALBlankLink();
            
          }
          
      }); 
      
      return this;
    
    
  } // TFALPost
  
  
  $.fn.TFALPostNav = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
      
      
          var $self   = $(this),
              $next   = $self.find('div#overlay-right'),
              $next_a = $next.find('a'),
              $prev   = $self.find('div#overlay-left'), 
              $prev_a = $prev.find('a'),
              $html   = ($.browser.mozilla || $.browser.msie) ? $('html') : $('body'),
              _iphone = ((navigator.userAgent.match(/Android/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
              
          $(document)
          .bind('KEYBOARD_RIGHT',on_key_right)
          .bind('KEYBOARD_LEFT',on_key_left)
          .bind('KEYBOARD_RELEASE',on_key_release);
          
          $next
          .css({display:'block'})
          .bind('click', function(e) { $self.triggerHandler('NEXT'); e.preventDefault() })
          .bind('mouseenter',on_next_enter)
          .bind('mouseleave',on_next_leave);
          
          
          $prev
          .css({display:'block'})
          .bind('click', function(e) { $self.triggerHandler('PREV'); e.preventDefault() })
          .bind('mouseenter',on_prev_enter)
          .bind('mouseleave',on_prev_leave);
          
          $(window)
          .bind('scroll',on_scroll);
          
          function on_key_right(e) {
          
            $next_a.addClass('key-active');
          
          }
          
          function on_key_left(e) {
          
            $prev_a.addClass('key-active');
            
          
          }
          
          function on_key_release(e) {
          
            $next_a.removeClass('key-active');
            
            $prev_a.removeClass('key-active');
          
          }
          
          
          function on_next_enter(e) {
          
            $next_a.stop();
            
            if (!_iphone && !$.TFALPost.tablet)
              $next.bind('mousemove',on_next_move)
          
          }
          
          function on_next_leave(e) {
          
            if(!_iphone && !$.TFALPost.tablet) {
            
              $next.unbind('mousemove',on_next_move)
            
              $next_a.animate({top:$html.attr('scrollTop') + 200},500,'easeInOutQuart')
              
            }
            
          }
          
          function on_next_move(e) {
          
            $next_a.css({top:e.pageY - $next.offset().top})
          
          }
          
          function on_prev_enter(e) {
          
            $prev_a.stop();
            
            if(!_iphone && !$.TFALPost.tablet)
              $prev.bind('mousemove',on_prev_move)
          
          }
          
          function on_prev_leave(e) {
          
            if (!_iphone && !$.TFALPost.tablet) {
            
              $prev.unbind('mousemove',on_prev_move)
            
              $prev_a.animate({top:$html.attr('scrollTop') + 200},500,'easeInOutQuart')
              
            }
          
          }
          
          function on_prev_move(e) {
          
            $prev_a.css({top:e.pageY - $prev.offset().top})
          
          }
          
          function on_scroll(e) {
            
            var t = (!_iphone && !$.TFALPost.tablet) ? $html.attr('scrollTop') + 200 : _getScroll().scrollTop
            
            $prev_a.css({top:t})
            
            $next_a.css({top:t})
            
          }
          
          function _getScroll(){
    				return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
		      }

      
      });
      
  }//TFAL
  
  

   $.fn.TFALPostContent = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
 
          var $body            = $('body'),
              $self            = $(this),
              xmlhttp_uri      = '',
              _offset          = 0,
              _append          = false,
              _loading          = false;
              
          $body
          .bind('FILTER',on_filter)
          .bind('APPEND',on_append)
          .bind('REPOST',on_repost);
          
          $.ajaxSetup({
			         cache: false,
			         dataType: 'html',
			         global: false,
			         timeout: 5000
		        });
		        
          function on_filter(e,uri,ignore) {
          
            if (!ignore) {
            
            xmlhttp_uri = uri;
            
            _offset = 0;
            
            _append = false;
            
            outro();
            
            }

          }
          
          function on_append(e,count) {
          
            
            _offset = count;
            
            _append = true;
            
            outro();
          

          }
          
          function on_repost(e,count) {
            
            xmlhttp_uri = '?offset='+count;
            
            outro();
          
          }
          
          function outro() {
          
          
          
           if (!_append) {
            $self.html('');
            
            $self
            .addClass('ajax-loading')
            .animate({opacity:1},750,'easeOutQuart',load)
            
           
           }else{
           
            load();
           
           }
            
          }
          
          function load() {
          
            _loading = true;
              
            $.ajax({
              beforeSend: before_send,
              error: on_error,
              success: on_success,
              data:{
                xmlhttp: true,
                offset: _offset
              },
              url: xmlhttp_uri
            });
            
          }
          
          function before_send() {
          
            if (!_append) {
              $body.triggerHandler('FILTER_OUT');
            }else{
              
              $('<div id="post-content-preloader"></div>').appendTo($self);
            
            }
            
          }
          
          function on_success(response) {
          
            if (!_append) {
            
              $self.css({opacity:0});    
            
            }
            
            $self.removeClass('ajax-loading')
                    
            $('#post-content-preloader').remove();
            
            $self.append(response).find('div[scope=PhotoGallery]').TFALPhotoGallery();
          
            $self.stop().animate({opacity:1},1000,'easeOutQuart')
            
            $body.triggerHandler('FILTER_APPLY',_append);
            
          }
          
          function on_error(e) {
          
          }
          
      
      });
      
    }
    
    
    
  

})(jQuery);


/* ---------------------------------- */

/* POST */

(function($) {

   $.fn.TFALCovers = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
      
        var $body            = $('body'),
            $self            = $(this),
            $pages           = $(this).find('.page');
        
            
        $pages.each(function(index) {
          
            if (index>0)
              $(this).css({opacity:0})
            else
              $(this).css({opacity:1})
        
        });
          
        $body
        .bind('COVER',on_show)
        
        function on_show(e,id) {
          
          $pages.each(function(index) {
          
            if (index<=id)
              $(this).stop().animate({opacity:1},600,'easeInOutQuart')
            else
              $(this).stop().animate({opacity:0},600,'easeInOutQuart')
            
            
          
          });
        
        }
            
      
      });
      
    }
    
    
})(jQuery);


/* ---------------------------------- */

/* PHOTOGALLERY */

(function($) {

  $.fn.TFALPhotoGallery = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
      
          if ($(this).hasClass('photogallery'))
            return;
      
          var $self       = $(this).addClass('photogallery'),
              $container  = $self.find('.photogallery-items'),
              $nav        = $('<div class="photogallery-nav"><span></span></div>').appendTo($self),
              $nav_items  = $nav.find('span'),
              $imgs       = $self.find('img'),
              $images     = new Array(),
              _maxHeight  = 0,
              _active     = 0,
              _total      = 0;
         
          $imgs.each(
          
            function(index) {
            
              var $img = $(this);
              
              if ($img.attr('height')>_maxHeight)
                _maxHeight = $img.attr('height');
            
              $img.css({left:300*index})
              
              $images.push($img); 
              
              _total++;
          
          });
          
          
          $self
          .css({height:_maxHeight})
          .bind('click',on_click);
          
          
          update_nav();
          
          function on_click(e) {
          
            $images[_active].animate({opacity:0},500,'easeInOutQuart')
            
            _active++;
            
            if (_active>=_total)
              _active = 0;
              
            $images[_active].animate({opacity:1},500,'easeInOutQuart')  
            
            $container.animate({left:-300*_active},400,'easeInOutQuart')
            
            update_nav();
          
          }
          
          function update_nav() {

            $nav_items.html((_active+1)+' of '+_total);
                      
          }
          
      });
      
  }//TFAL
    
  

})(jQuery);


 



/* ---------------------------------- */

/* FILTERS */

(function($) {


   $.fn.TFALFilters = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
    
   
  
      this.each(function(index) { 
 
          var $body          = $('body'),
              $self          = $(this),
              $nav           = $('div#nav'),
              $navfilter     = $('li[scope=NavFilter]'),
              $navlink       = $navfilter.find('a'),
              $navfilterspan = $navfilter.find('span'),
              _open          = false;
          
          $navfilter.addClass('active');
          
          $self
          .bind(config.EVENT, toggle)
        
          $body
          .bind('FILTER',on_filter);
          
          $navlink
          .bind('click',on_toggle_click);
          
          $(document)
          .bind('KEYBOARD_KEY',on_keyboard_key)
                  
          $self.find('ul[scope=FilterSet]').TFALFilterSet();
          
          $self.find('ul[scope=CoverSet]').TFALFilterSet({'cover':true});
          
          
          function on_toggle_click(e) {
              
              $self.triggerHandler(config.EVENT);
              
              if (config.GLOBAL) $('body').triggerHandler(config.EVENT);
              
              e.preventDefault();
          }
          
          function on_keyboard_key(e,id){
          
            if (id=="x")
              toggle();
          
          }
          
          function toggle(e) {
          
            if (!_open)
              open();
            else
              close();
          
          }
          
          function open() {
          
            _open = true;
            
            $self.stop().animate({height:$('#filters-content').outerHeight()+42},750,'easeOutQuint');
			$self.stop().animate({height:100},750,'easeOutQuint');
                        
          }
          
          function close() {
          
            _open = false;
            
            $self.stop().animate({height:200},750,'easeOutQuint',function(){$nav.removeClass('active')});
			 $self.stop().animate({height:0},200,'easeOutQuint',function(){$nav.removeClass('active')});
            
          }
          
          function on_filter(e,id) {
          
            close();
            
          }
          
      }); 
      
      return this;
    
    
  } // FILTERS
  
  
  $.fn.TFALFilterSet = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
 
          var $self     = $(this),
              _active   = false;
          
          if (config.cover==true)
            $self.find('li').TFALCoverFilter();
          else
            $self.find('li').TFALFilter();
                
      }); 
      
      return this;
    
    
  } // FILTERSET
  
  
  $.fn.TFALFilter = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
    
    var $active_index = 0;
    
      this.each(function(index) { 
 
          var $body     = $('body'),
              $self     = $(this),
              $a        = $self.find('a'),
              $em       = $('<em/>').appendTo($self),
              _href     = $a.attr('href'),
              _active   = false;
              
              if ($a.attr('rev')!='DeliciousLink'){
              
                $a.each(function(){$(this).bind('click',on_click)});
              
                $em.bind('click',on_click);
              
              }
              
              $body.bind('FILTER',on_filter);
              
              function on_click(e) {
              
                if ($self.hasClass('active'))
                  $body.triggerHandler('FILTER',_href.split(":")[0]);
                else
                  $body.triggerHandler('FILTER',_href);
                
                e.preventDefault();
              
              }
              
              function on_filter(e,id) {

                if (id==_href)
                  $self.addClass('active');
                else
                  $self.removeClass('active');
              
              }
              
              
              
                 
      }); 
      
      return this;
    
    
  } // FILTER
  
  $.fn.TFALCoverFilter = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
     //global
    
    var $active_index = 0,
        $cover_items = new Array();
    
      this.each(function(index) { 
 
          var $body     = $('body'),
              $self     = $(this),
              $a        = $self.find('a'),
              $em       = $('<em/>').appendTo($self),
              _href     = $a.attr('href'),
              _rev      = $a.attr('rev');
              
              $cover_items.push(_href);
              
              $a
              .bind('click',on_click);
              
              $body
              .bind('ARROW_NEXT',on_arrow_next)
              .bind('ARROW_PREV',on_arrow_prev);
              
              
              function on_click(e) {
              
              
              }
              
              function on_arrow_next(e,id) {
                
                if (id==_rev && index<$cover_items.length-1){
                
                  location.href = $cover_items[index+1];
                  
                }
              
              }
              
              function on_arrow_prev(e,id) {
                
                if (id==_rev && index>0){
                
                  location.href = $cover_items[index-1];
                  
                }
              
              }
              
              
                 
      }); 
      
      return this;
    
    
  } // FILTER
  

})(jQuery);



/* ---------------------------------- */

/* DELICIOUS */

(function($) {

  
   $.fn.TFALDeliciousLink = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $body = $('body'),
            _id   = $self.attr('rel'),
            _href = $self.attr('href');
            
        
        $self.bind('click',on_click);
        
        function on_click(e) {
        
        
          $body.triggerHandler('DELICIOUS',_id);
          
          $body.triggerHandler('FILTER',[_href,true])
          
          e.preventDefault();
          
        
        }
        
        
            
     });
   
   }

   $.fn.TFALDelicious = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
      
        var $self = $(this),
            $body = $('body');

            $body
            .bind('DELICIOUS',on_delicious)
            
            $('a[rev=DeliciousLink]').TFALDeliciousLink();
            
            $self.find('a').each(function(){$(this).TFALBlankLink()})
            
            function on_delicious(e,id) {
            
                    
                    
                    $self
                    .html('')
                    .addClass('ajax-loading')
                    
                    
                    $.ajax({ 
      		      
      		               type: "GET",
			                   dataType: "jsonp",
			                   url:'http://feeds.delicious.com/v2/json/thinkingforaliving/'+id+'?count=100',
                  			 success:          
                  			   function(resultset){
                              
                              
                              
                              var r_count  = 0,
                                  c_count  = 0,
                                  $columns = new Array( $('<div/>').addClass('grid2 page column') );
                              
                              
                              $.each(resultset, function(i,item){
                              
                                var delicious_link = $("<div/>")
                                    .addClass('delicious-link')
                                    .append($("<h1/>").html('<a href="'+item.u+'">' + item.d + "</a>"))
                                    .append($('<p/>').html(item.n));
                                
                                                      
                                if ( r_count%5==0 ) {
                                
                                  $self.append( $columns[c_count] );
                                
                                  $columns.push( $('<div/>').addClass('grid2 page column') );
                                
                                  c_count++;
                                  
                                }else{
                                
                                  delicious_link.appendTo( $columns[c_count] );
                                
                                }
                               
                                r_count++;
                                
                                
                                 $self
                                 .removeClass('ajax-loading')
                                 .css({opacity:0})
                                 .animate({opacity:1},500,'easeInOutQuart'); 
                                
                              }); 
                              
                              
                              $self.append( $columns[c_count] );
                              
                              $self.find('a').each(function(){$(this).TFALBlankLink()})
                            
                           }
                         
                       });
                       
                       
                       
              }
                       
      });
      
  }//TFAL
    

})(jQuery);   



/* ---------------------------------- */

/* QUOTE */

(function($) {

  $.fn.TFALCoverQuote = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
      
      
          var $self = $(this),
              $h2   = $self.find('h2'),
              $qm1   = $('<span />').addClass('q1').html('&#8220;').appendTo($h2),
              $qm2   = $('<span />').addClass('q2').html('&#8221;').appendTo($h2);
              
      });
      
  }//TFAL
    
  

})(jQuery);                  


/* ---------------------------------- */

/* KEYBOARD */

(function($) {


   $.fn.TFALKeyboard = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
        
        var _active         = true,
            _commandControl = false;

        $(this)
        .bind('keydown',on_keydown)
        .bind('keyup',on_keyup);
        
        $(this)
        .bind('IGNORE_KEYBOARD',on_ignore)
        .bind('ACTIVATE_KEYBOARD',on_activate);
         
        function on_ignore(e) {
        
          _active = false;
          
        }
        
        function on_activate(e) {
        
          _active = true;
        
        }
        
        function on_keyup(e) {
        
          _commandControl = false;
          
          $(this).triggerHandler('KEYBOARD_RELEASE');
        
        }
        
        function on_keydown(e) {
    
          if (_active) {
          
    		  var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
    		  
          switch(key) {
             
             case 17: //control
             case 91: //command
             
               _commandControl = true;
              
             break;
             
             case 90: // Command-Z :)
              
             if (_commandControl) 
              history.go(-1); 
              
             break;
            
             case 38: //top
              
              $(this).triggerHandler('KEYBOARD_UP');
              e.preventDefault();
                        
             break;
           
             case 39: //right

              $(this).triggerHandler('KEYBOARD_RIGHT');
              e.preventDefault();
              
             break;
             
             case 40: ///bottom
            
              $(this).triggerHandler('KEYBOARD_DOWN');
              e.preventDefault();
                        
             break;
              
             case 37: //left
             
              $(this).triggerHandler('KEYBOARD_LEFT');
              e.preventDefault();
                        
             break;
             
             case 70: //f
              
              $(this).triggerHandler('KEYBOARD_KEY',"f");
              
                        
             break;
             
             case 67: //c
             
              if (!_commandControl) 
                $(this).triggerHandler('KEYBOARD_KEY',"c");
              
                        
             break;
             
             case 78: //n
              
              $(this).triggerHandler('KEYBOARD_KEY',"n");
              
                        
             break;
             
             case 68: //d
             
              $(this).triggerHandler('KEYBOARD_KEY',"d");
              
                        
             break;
             
             case 83: //s
             
             $(this).triggerHandler('KEYBOARD_KEY',"s");
              
                        
             break;
             
             case 84: //t
             
             $(this).triggerHandler('KEYBOARD_KEY',"t");
              
                        
             break;
             
             case 88: //x
             
             $(this).triggerHandler('KEYBOARD_KEY',"x");
              
                        
             break;
             
        
          }//switch


        
          } //if
          
        }//keydown
      
        
        
            
      }); 
      
      return this;
    
    
  } // ARROW-KEYBOARD
  

})(jQuery);



/* ---------------------------------- */

/* LINKS */

(function($) {

  
   $.fn.TFALBlankLink = function() {
   
     this.each(function() { 
      
        var $self = $(this);
            
        
        $self
        .attr('target','_blank')
        .bind('click',on_click);
        
        function on_click(e){
        
          
        
        }
        
            
     });
     
    }
    
    $.fn.TFALSiteOverview = function() {
   
     this.each(function() { 
      
        var $self = $(this);
            
        
        $self
        .bind('click',on_click);
        
        function on_click(e){
        
          location.href="/archives/4580";
        
        }
        
            
     });
     
    }

    
})(jQuery);


