

jQuery(function($) {
	if ($('.feedreading_blogroll_bookmarklist').length > 0){
		$.getScript("http://www.google.com/jsapi?key=ABQIAAAAzDl-Mb42bHKg9bRek4oa7BS8Wunx-143_AL6XRnvjNpXOAjLiRQp1DDoBL8fJzRG-uHPOOl-1GKpmA", 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(feed.description);
                                        $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});
				}

                                			$title.html(entry.title);
			$title.attr( {
				href  : entry.link,
				title : $("<p></p>").html(entry.contentSnippet).html(),
				rel   : "external",
				rev   : "bookmark"
			});

			/*$title.parent().append($("<a></a>").attr({
					href : entry1.link,
					title: $("<p></p>").html(entry1.contentSnippet).html(),
					rel   : "external",
					rev   : "bookmark"
			}).html(entry1.title));*/
                                return false;
            }
            /* add "very old" age to bookmarks with no feed-url */
            function addZeroAge(zeroAgeBookmark){
                var $zali =$(zeroAgeBookmark),
                randomAge = Math.floor(Math.random()*10000001);
                if ($zali !== null ) {
                    $zali.attr({age:randomAge});
                }
                return false;
            }

            /* 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));
                    return false;
            }

			/*
			 *
			 */
            function feedreading_limit_display(){ 
            	var
                 liArraySingle_3 = $("#single-3_feedreading_blogroll_ > li") ;					for (var i=0; i < liArraySingle_3.length; i++) { 
						if(i > -1){
	        				$(liArraySingle_3[i]).css("display","none");
						}
					} 				return false;
        	}
        	
            /*
             * Sort the blogroll with tsort()
             */
            function feedreading_automatic_sort() {                 		var $allCompleted ,
										$hasCompleteAgeSingle3=true, isCompleteSingle3=false, $liSortSingleArray3= $("#single-3_feedreading_blogroll_ > li") 
					;	        		for (var i=0; i < $liSortSingleArray3.length; i++) {
						var $age3 = $($liSortSingleArray3[i]).attr("age");
						if ($age3 === null || $age3 == "" || isNaN($age3)) {
							$hasCompleteAgeSingle3 = false;
						}
	        		}
					

					if ($hasCompleteAgeSingle3 && !isCompleteSingle3) {
						try{
							//$("#single-3_feedreading_blogroll_ > li").tsort({order:"desc",attr:"age"});
							$("#single-3_feedreading_blogroll_ > li").frbrsort(sortAlpha).appendTo("#single-3_feedreading_blogroll_");
							isCompleteSingle3=true;
						} catch (e){
							// do nothing
						}
					}
									$allCompleted =
									isCompleteSingle3					;				
				if ($allCompleted){
				clearInterval(myInterval);
												}
								return false;
            }

	function feedreading_rolling(){
						var
						$single_blogroll_3 = $('#single-3_feedreading_blogroll_'), $single_blogroll_3_size=$single_blogroll_3.find('li').size() , $single_blogroll_3_limit = ($single_blogroll_3_size>5)? (5): ($single_blogroll_3_size-1) 
						;
			
						
						if ($single_blogroll_3_size > 1) {
				$("#single-3_feedreading_blogroll_ > li").css("display","none");
				$single_blogroll_3.feedReadingBlogrollSpy($single_blogroll_3_limit,4000);
			}

					return false;
	}

            /*
             * add observer to blogroll()
             */
	function feedreading_category_observer() {
	    		$("#widget_feedreading_blogroll, .widget_feedreading_blogroll").bind("change click keypress", function(event){
			var $eventTarget = $(event.target), $previewtarget = "#"+$eventTarget.parent().children(".previewtarget").text();
						if ($eventTarget.is('abbr')){
				$eventTarget.parent().parent().children(".preview_wrap").toggle("slow");
			}
			if ($eventTarget.is('small')){
				$eventTarget.parent().parent().parent().children(".preview_wrap").toggle("slow");

			}
						
					});
				$("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");
		});
		return false;
	}
					            /* 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() { 
									var 					feed11 = new google.feeds.Feed("http://feeds.mashable.com/Mashable")
					,feed_single311  = new google.feeds.Feed("http://feeds.mashable.com/Mashable")
						;                        if($("#feedreading_bookmark_11").length > 0){
                                      feed11.load(function(result_11){
                                      if (!result_11.error) {
                                      addAge(result_11.feed, "#feedreading_bookmark_11", "#feedreading_anchor_11", "#feedreading_info_11", "#feedreading_previewtoggle_11", "#frbl_last_posttitle_11");
                                      addFeedControl("#feedreading_preview_11", "http://feeds.mashable.com/Mashable", "Mashable");
    												} else {
                  			addZeroAge("#feedreading_bookmark_11");
              			}
                                      });}
                                                                if($("#feedreading_bookmark_12").length > 0){
                          
						google.feeds.lookupFeed("http://wired.com", function() {
							var url12= this.url, feed12 = new google.feeds.Feed(this.url);
                            feed12.load(function(result_12){
                                if (!result_12.error) {
                                addAge(result_12.feed, "#feedreading_bookmark_12", "#feedreading_anchor_12", "#feedreading_info_12", "#feedreading_previewtoggle_12", "#frbl_last_posttitle_12");
                                addFeedControl("#feedreading_preview_12", url12, "WIRED");
						                  			} else {
                      			addZeroAge("#feedreading_bookmark_12");
                  			}
                                });

						});}

                                          
																														// hallo
										if($("#single-3_feedreading_bookmark_11").length > 0){

										feed_single311.load(function(result_single_311){
										if (!result_single_311.error) {
											addAge(result_single_311.feed, "#single-3_feedreading_bookmark_11", "#single-3_feedreading_anchor_11", "#single-3_feedreading_info_11", "#single-3_feedreading_previewtoggle_11", "#single-3_frbl_last_posttitle_11");
											addFeedControl("#single-3_feedreading_preview_11", "http://feeds.mashable.com/Mashable", "Mashable");
																					} else {
												addZeroAge("#single-3_feedreading_bookmark_11");
											}
										});
										}
										                    											if($("#single-3_feedreading_bookmark_12").length > 0){
											google.feeds.lookupFeed("http://wired.com", function() {
											var url_single_312= this.url, feed_single_312 = new google.feeds.Feed(this.url);
											feed_single_312.load(function(result_single_312){
											if (!result_single_312.error) {
											addAge(result_single_312.feed, "#single-3_feedreading_bookmark_12", "#single-3_feedreading_anchor_12", "#single-3_feedreading_info_12", "#single-3_feedreading_previewtoggle_12", "#single-3_frbl_last_posttitle_12");
																					addFeedControl("#single-3_feedreading_preview_12", url_single_312, "WIRED");
																					} else {
											addZeroAge("#single-3_feedreading_bookmark_12");
											}
										});
									});}
                                          																											feedreading_category_observer();
				return false;
                }


      $.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));
    	        });
    	        /*for (var i=0; i < li_items.length; i++){
    	            //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();
    	    });
    	};
    	$.fn.frbrsort = function() {
    		return this.pushStack( [].sort.apply(this, arguments), []);
    	};

    	function sortAlpha(a, b) {
    		return parseInt($(a).attr("age")) < parseInt($(b).attr("age")) ? 1 : -1;
    	};
});
            
                    