

jQuery(function($) {
	if ($('.feedreading_blogroll_bookmarklist').length > 0){
		$.getScript("http://www.google.com/jsapi?key=ABQIAAAAPgnXAXTzVdorySxicTzVshS0EmZWuBRzd6OR_tyBJVlmFpC_2BRFP-1FuOrjslwXFTC8aBXLkyUIEw", 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("hace %d  d&iacute;as", days);
                } else if (days==1){
                	return "ayer ";
                } else if (days< 1 && hours > 1) {
                	return String.sprintf("Hace %d horas", hours);
                } else if (days< 1 && hours == 1) {
                	return "en la &uacute;ltima hora";
                } else if (days < 1 && hours < 1) {
                	return "hace un rato";
                }
            }
            /* 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, author="";
                entry = feed.entries[0]
                /*,entry1= feed.entries[1] */;
                try {
                    then = new Date(entry.publishedDate).getTime();
                } catch (dateException) {
                    // do noting
                }
                                if(!(entry.author===null || entry.author == "")){
                    author = entry.author;
                } else {
                    if(!(feed.author===null || feed.author == "")){
                    	author = feed.author;
                    }
                }
                
                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));
					           
                                        if (author!= "" ) {
	                    ageMsg.push(" por ");
	                    ageMsg.push(author);
                    }
                                        $toggle.html(ageMsg.join('')).attr({feedurl:feed.link});
                }
                                			$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
                 liArray = $("#feedreading_blogroll_ > li");					for (var i=0; i < liArray.length; i++) { 
						if(i > 14){
	        				$(liArray[i]).css("display","none");
						}
					} 				return false;
        	}
        	
            /*
             * Sort the blogroll with tsort()
             */
            function feedreading_automatic_sort() { 					var $allCompleted=false, $hasCompleteAge=true, isComplete=false, $sortArray=$("#feedreading_blogroll_ >li") 
										;
	        		for (var i=0; i < $sortArray.length; i++) {
						var $age_ = $( $sortArray[i]).attr("age");
						if ($age_ === null || $age_ == "" || isNaN($age_)) {
							$hasCompleteAge = false;
						}
	        		}
	        		if($sortArray.length==0){
	        			$hasCompleteAge = true;
	        		}
											if ($hasCompleteAge && !isComplete){
							try{
							//$("#feedreading_blogroll_ > li").tsort({order:"desc",attr:"age"});
							$("#feedreading_blogroll_ > li").frbrsort(sortAlpha).appendTo("#feedreading_blogroll_ ");							
							isComplete=true;
							} catch (e){
							// do nothing
							}
						}

						
					$allCompleted = $hasCompleteAge 
					;							
					if ($allCompleted) {
						clearInterval(myInterval);
													feedreading_limit_display();
																	}
									return false;
            }

	function feedreading_rolling(){
						var
							$blogroll_all= $('#feedreading_blogroll_'), $blogroll_all_size= $blogroll_all.find('li').size(), $blogroll_all_limit = ($blogroll_all_size>5)? (5): ($blogroll_all_size-1)
						;
			
						$('#feedreading_blogroll_ > li').css("display","none");
			$blogroll_all.feedReadingBlogrollSpy($blogroll_all_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 					feed13 = new google.feeds.Feed("http://criminalgeographic.blogspot.com/feeds/posts/default")
					,					feed14 = new google.feeds.Feed("http://mensrea-actusreus.blogspot.com/feeds/posts/default")
					,					feed15 = new google.feeds.Feed("http://feeds.feedburner.com/blogspot/mhgV")
					,					feed16 = new google.feeds.Feed("http://feeds.feedburner.com/blogspot/LPpu")
					;                      if($("#feedreading_bookmark_12").length > 0){
                          
						google.feeds.lookupFeed("http://seccif.wordpress.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, "Sociedad Española de Criminologia y ciencias Forenses");
						                  			} else {
                      			addZeroAge("#feedreading_bookmark_12");
                  			}
                                });

						});}

                                                                  if($("#feedreading_bookmark_13").length > 0){
                                      feed13.load(function(result_13){
                                      if (!result_13.error) {
                                      addAge(result_13.feed, "#feedreading_bookmark_13", "#feedreading_anchor_13", "#feedreading_info_13", "#feedreading_previewtoggle_13", "#frbl_last_posttitle_13");
                                      addFeedControl("#feedreading_preview_13", "http://criminalgeographic.blogspot.com/feeds/posts/default", "Criminal Geographic");
    												} else {
                  			addZeroAge("#feedreading_bookmark_13");
              			}
                                      });}
                                                                  if($("#feedreading_bookmark_14").length > 0){
                                      feed14.load(function(result_14){
                                      if (!result_14.error) {
                                      addAge(result_14.feed, "#feedreading_bookmark_14", "#feedreading_anchor_14", "#feedreading_info_14", "#feedreading_previewtoggle_14", "#frbl_last_posttitle_14");
                                      addFeedControl("#feedreading_preview_14", "http://mensrea-actusreus.blogspot.com/feeds/posts/default", "Mens rea actus reus");
    												} else {
                  			addZeroAge("#feedreading_bookmark_14");
              			}
                                      });}
                                                                  if($("#feedreading_bookmark_15").length > 0){
                                      feed15.load(function(result_15){
                                      if (!result_15.error) {
                                      addAge(result_15.feed, "#feedreading_bookmark_15", "#feedreading_anchor_15", "#feedreading_info_15", "#feedreading_previewtoggle_15", "#frbl_last_posttitle_15");
                                      addFeedControl("#feedreading_preview_15", "http://feeds.feedburner.com/blogspot/mhgV", "El laboratorio de Gwen");
    												} else {
                  			addZeroAge("#feedreading_bookmark_15");
              			}
                                      });}
                                                                  if($("#feedreading_bookmark_16").length > 0){
                                      feed16.load(function(result_16){
                                      if (!result_16.error) {
                                      addAge(result_16.feed, "#feedreading_bookmark_16", "#feedreading_anchor_16", "#feedreading_info_16", "#feedreading_previewtoggle_16", "#frbl_last_posttitle_16");
                                      addFeedControl("#feedreading_preview_16", "http://feeds.feedburner.com/blogspot/LPpu", "El investigador");
    												} else {
                  			addZeroAge("#feedreading_bookmark_16");
              			}
                                      });}
                                                                if($("#feedreading_bookmark_17").length > 0){
                          
						google.feeds.lookupFeed("http://barbagris-tedax.blogspot.com/", function() {
							var url17= this.url, feed17 = new google.feeds.Feed(this.url);
                            feed17.load(function(result_17){
                                if (!result_17.error) {
                                addAge(result_17.feed, "#feedreading_bookmark_17", "#feedreading_anchor_17", "#feedreading_info_17", "#feedreading_previewtoggle_17", "#frbl_last_posttitle_17");
                                addFeedControl("#feedreading_preview_17", url17, "Cronicas del TEDAX Barbagris");
						                  			} else {
                      			addZeroAge("#feedreading_bookmark_17");
                  			}
                                });

						});}

                                          
																																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;
    	};
});
            
                    