

jQuery(function($) {


	google.load("feeds", "1",{"callback" : initializeBR});
	//initializeBR();

			/**
			 * printf() for Javascript
			 */
			function sprintf() {
                if( sprintf.arguments.length < 2 ) {
                    return;
                }
                var data = sprintf.arguments[ 0 ];
                for( var k=1; k<sprintf.arguments.length; ++k ) {
                    switch( typeof( sprintf.arguments[ k ] ) ){
                        case 'string':
                            data = data.replace( /%s/, sprintf.arguments[ k ] );
                            break;
                        case 'number':
                            data = data.replace( /%d/, sprintf.arguments[ k ] );
                            break;
                        case 'boolean':
                            data = data.replace( /%b/, sprintf.arguments[ k ] ? 'true' : 'false' );
                            break;
                            default:
                           /// function | object | undefined
                        break;
                    }
                }
                return(data);
            }
            if( !String.sprintf ) {
            	String.sprintf = sprintf;
            }


            /**
             * generate text showing the age of the bookmark's latest post
             */
            function getAge(days, hours){
                if (days > 1) {
                    return String.sprintf("%d days ago", days);
                } else if (days==1){
                	return "yesterday ";
                } else if (days< 1 && hours > 1) {
                	return String.sprintf("%d hrs ago", hours);
                } else if (days< 1 && hours == 1) {
                	return "in the last hour";
                } else if (days < 1 && hours < 1) {
                	return "just recently";
                }
            }
            /* add age and other info to bookmark*/
            function addAge(feed, bookmark, anchor, divID, previewtoggle, last_posttitle){
                var $li =$(bookmark),
                 $a =$(anchor),
                 $toggle =$(previewtoggle),
                 $title =$(last_posttitle),
                 now = (new Date()).getTime(),
                 then = (new Date()).getTime(),
                 ageInDays,
                 ageInHours,
                 randomAge,
                 ageMsg=[],
                 $snippet,
                 entry;
                entry = feed.entries[0]
                /*,entry1= feed.entries[1] */;
                try {
                    then = new Date(entry.publishedDate).getTime();
                } catch (dateException) {
                    // do noting
                }
                
                ageInDays =  Math.floor((now-then)/(1000*60*60*24)),
                ageInHours = Math.floor((now-then)%(1000*60*60*24)/3600000);

                try {
                    $entryTitle =$("<p></p>").html(entry.title);
                    $a.attr({title: $entryTitle.html()});
                } catch (titleException) {
                    $a.attr({title: ""});
                }
				if (!isNaN(then)){
					// insert age into list-item to allow sorting by age of post
                    $li.attr({age:then});
				} else {
		            /* add "very old" age to bookmarks with no feed-url */
					randomAge = Math.floor(Math.random()*1000001);
					$li.attr({age:randomAge});
				}

                                if (!(isNaN(ageInDays) || isNaN(ageInHours))){
                    ageMsg.push(getAge(ageInDays, ageInHours));
					           
                                        $toggle.html(ageMsg.join('')).attr({feedurl:feed.link});
                }
                                                return;
            }
            /* add "very old" age to bookmarks with no feed-url */
            function addZeroAge(zeroAgeBookmark){
                var $zali =$(zeroAgeBookmark),
                randomAge = Math.floor(Math.random()*1000001);
                if ($zali !== null ) {
                    $zali.attr({age:randomAge});
                }
                return;
            }

            /* add jQuery-oberserver to enable mouse-clicks*/
            function addFeedControl(preview, feed, name){
                    var feedControl = new google.feeds.FeedControl();
                    feedControl.addFeed(feed, name);
                    feedControl.draw($(preview).get(0));
            }

			/*
			 *
			 */
            function feedreading_limit_display(){         				$.each($("#feedreading_blogroll_2 > li"), function(i2, $element2){
            				if(i2 > -1){
                				$($element2).css("display","none");
            				}
        				});
      				        				$.each($("#feedreading_blogroll_3 > li"), function(i3, $element3){
            				if(i3 > -1){
                				$($element3).css("display","none");
            				}
        				});
      				        }
            /*
             * Sort the blogroll with tsort()
             */
            function feedreading_automatic_sort() { 			var $allCompleted ,
			            				$hasCompleteAge2=true, isComplete2=false
          				 ,             				$hasCompleteAge3=true, isComplete3=false
          				;
					$.each($("#feedreading_blogroll_2>li"), function(idx2, $elem2) {
						var $age2 = $($elem2).attr("age");
						if ($age2 === null || $age2 == "" || isNaN($age2)) {
							$hasCompleteAge2 = false;
						}
					});


					if ($hasCompleteAge2 && !isComplete2) {
						$("#feedreading_blogroll_2>li").tsort({order:"desc",attr:"age"});
						isComplete2=true;
					}
          				
					$.each($("#feedreading_blogroll_3>li"), function(idx3, $elem3) {
						var $age3 = $($elem3).attr("age");
						if ($age3 === null || $age3 == "" || isNaN($age3)) {
							$hasCompleteAge3 = false;
						}
					});


					if ($hasCompleteAge3 && !isComplete3) {
						$("#feedreading_blogroll_3>li").tsort({order:"desc",attr:"age"});
						isComplete3=true;
					}
          								$allCompleted =
									            				$hasCompleteAge2          									 &&             				$hasCompleteAge3          				;				
				if ($allCompleted){
				clearInterval(myInterval);
												}
				            }

	function feedreading_rolling(){
						var
				         							
			$blogroll_2 = $('#feedreading_blogroll_2'), $blogroll_2_size=$blogroll_2.find('li').size() , $blogroll_2_limit = ($blogroll_2_size>5)? (5): ($blogroll_2_size-1) 
			,	         							
			$blogroll_3 = $('#feedreading_blogroll_3'), $blogroll_3_size=$blogroll_3.find('li').size() , $blogroll_3_limit = ($blogroll_3_size>5)? (5): ($blogroll_3_size-1) 
						;
			
						
				         							
				if ($blogroll_2_size > 1) {
					$("#feedreading_blogroll_2 > li").css("display","none");
					$blogroll_2.feedReadingBlogrollSpy($blogroll_2_limit,4000);
				}
					         							
				if ($blogroll_3_size > 1) {
					$("#feedreading_blogroll_3 > li").css("display","none");
					$blogroll_3.feedReadingBlogrollSpy($blogroll_3_limit,4000);
				}
					}

            /*
             * add observer to blogroll()
             */
	function feedreading_category_observer() {
	    		$("ul.feedreading_blogroll_bookmarklist").bind("mouseenter",function(event){
			var $eventTarget =$(event.target);
			$eventTarget.parents(".feedreading_blogroll_bookmarklist").addClass("mouseover");
		});
		$("ul.feedreading_blogroll_bookmarklist").bind("mouseleave",function(event){
			var $eventTarget =$(event.target);
			$eventTarget.parents(".feedreading_blogroll_bookmarklist").removeClass("mouseover");
		});
	}
					            /* call sort-function every half second */
		            var myInterval = window.setInterval(function (){feedreading_automatic_sort(); },1000);
			/* stop calling sort-function after n seconds */
			window.setTimeout(function (a,b){
				clearInterval(myInterval);
			}, 20000);
			
      function initializeBR() { 						google.feeds.lookupFeed("http://www.yoshisisland.net/", function() {
							var url35= this.url, feed35 = new google.feeds.Feed(this.url);
                            feed35.load(function(result_35){
                                if (!result_35.error) {
                                addAge(result_35.feed, "#feedreading_bookmark_35", "#feedreading_anchor_35", "#feedreading_info_35", "#feedreading_previewtoggle_35", "#frbl_last_posttitle_35");
                  			} else {
                      			addZeroAge("#feedreading_bookmark_35");
                  			}
                                });

						});

                                          
																																feedreading_category_observer();
                }


      $.fn.feedReadingBlogrollSpy = function (limit, interval) {
    	    limit = limit || 4;
    	    interval = interval || 4000;

    	    return this.each(function () {
    	        // 1. setup
    	            // capture a cache of all the list items
    	            // chomp the list down to limit li elements
    	        var $list = $(this),
    	            items = [], // uninitialised
    	            currentItem = limit,
    	            total = 0, // initialise later on
    	            height = $list.find('li:first').height();

    	        // capture the cache
    	        $list.find('li').each(function () {
    	            //items.push('<li>' + $(this).html() + '</li>');
    	            items.push($(this));
    	        });

    	        total = items.length;

    	        $list.wrap('<div class="spyWrapper" />').parent().css({ height : height * (limit + 2) });

    	        $list.find('li').filter(':gt(' + (limit - 1) + ')').remove();

    	        // 2. effect
    	        function spy() {
			if(!$list.hasClass("mouseover")){
			    // insert a new item with opacity and height of zero
			    var $insert = $(items[currentItem]).css({
				height : 0,
				opacity : 0,
				display : 'none'
			    }).prependTo($list);

			    // fade the LAST item out
			    $list.find('li:last').animate({ opacity : 0}, 1000, function () {
				// increase the height of the NEW first item
				$insert.animate({ height : height }, 1000).animate({ opacity : 1 }, 1000);

				// AND at the same time - decrease the height of the LAST item
				// $(this).animate({ height : 0 }, 1000, function () {
				    // finally fade the first item in (and we can remove the last)
				    $(this).remove();
				// });
			    });

			    currentItem++;
			    if (currentItem >= total) {
				currentItem = 0;
			    }
			}
			setTimeout(spy, interval)
    	        }

    	        spy();
    	    });
    	};
});
            
                    