/*
*	jquery.BBCHeadline.js
*	AllofUs
*	Written by Nic Mulvaney (nic@allofus.com)
*
*	This plugin fetches headlines from BBC RSS feeds.
*	For use with the 'World Service Language Select' page.
*
*/




// RSS Feed wrapper - This is for offline mode (uses yahoo pipes)
function RSSFeed(){}
// Yahoo pipe for turning an RSS XML feed into JSONP
// http://pipes.yahoo.com/pipes/pipe.info?_id=37a11b5d21842bca434322d23b963d5e
RSSFeed.Entries = function(feed_url, callback){
    requestURL = "http://pipes.yahoo.com/pipes/pipe.run?_id=e7d1a6cba080b7998f2706d3741f11ad&_render=json&_callback=?&url=" + feed_url;
    $.getJSON(requestURL, function(json, status){
        callback(json.value.items, status);
    });
}

function loadTest(url,obj){
	RSSFeed.Entries(url, function(json, status){
	    var content = "";
	    $.each(json, function(i){
	    	var headlineData = {title:this['title'],url:this['link'],img:'',intro:defaultMessage};
	    	formatHeadline(obj, headlineData);
	    })
	});
}




(function($) {

	
	// Begin Plugin
	$.fn.BBCHeadline = function(options) {
	var opts = $.extend({}, $.fn.BBCHeadline.defaults, options);
	
	// What is this?
	_obj = this;
	
	// Add a loading icon
	_obj.each(function() {
		$(_obj).html("<img src='images/overlay/ajax-loader.gif' class='loading-icon'>").hide().fadeIn("fast");
	});
	
	// Load the feed
	$.log("start loading:"+opts.url);
	
	if(!onlineMode){
		loadTest(opts.url,$(_obj));
		return false;
	}else{
	
		req = $.ajax({
		  type: "GET",
		  url:opts.url,
		  dataType: "xml",
		  success: function(xml){
		  		// Find the first Item in the rss feed
		  		var node = $(xml).find('entry:eq(0)');
		  		
		  		if(!node.length){
		  		node = $(xml).find('item:eq(0)');
		  		}
		  		
		  		// Get the title
	  			var title = node.find('title:eq(0)').text();
	  			
	  			// Get an image
	  			var img = node.find('img:eq(0)').attr("src");
	  			
	  			// RSS 1
	  			if(!img){
	  			img = node.find('[nodeName=xhtml:img]:eq(0)').attr("src");
	  			}
	  			
	  			// RSS 2
		  		if(!img){
		  		img = node.find('[nodeName=media:thumbnail]:eq(0)').attr("url");
		  		}
		  		
	  			// STILL NO IMAGE? Have another go...
		  		if(!img){
		  		img = node.find('[nodeName=image:item]:eq(0)').attr("rdf:about");
		  		}	
		  		
	  			
	  			// Get a link
	  			var url = node.find('link:eq(0)').attr("href");
		  		if(!url){
		  		url = node.find('link:eq(0)').text();
		  		}
	  			
	  			// Create Object
	  			var headlineData = {
	  				title:title,
	  				img:img,
	  				url:url,
	  				intro:opts.intro
	  			};
	  			
	  			
	  			// Print it to all the Objects
		  		return _obj.each(function() {
		  			$.fn.BBCHeadline.format($(_obj), headlineData);
				});
				
				//return false;
	   	  },
	   	  error: function (XMLHttpRequest, textStatus, errorThrown){
		  		return _obj.each(function() {
		  			// HIDE ERROR CALLBACKS
		  			//$(_obj).html("Error loading headline");
					 //$(_obj).html("Error: "+XMLHttpRequest.statusText+" - "+textStatus+"<br>"+errorThrown);
				});
	   	  },
	   	  timeout: 5000
	
		});
		
	}

	
	$.fn.BBCHeadline.format = function(obj, data){
		sLoad = true;
		if(data.img){
			obj.image(data.img,function(){
				obj.hide().append(wbr(data.title,6)).wrapInner("<a href='"+data.url+"'></a>").find("img").addClass("headline-image");
				if(ie==6){
					//obj.show();
					expandPanel();
				}else{
					//obj.fadeIn("fast");
					expandPanel();
				}
				
			},function(){
			
				$.error("No Image available with this news story");
				obj.hide().empty().append("<b>"+data.intro+"</b> "+wbr(data.title,6)).wrapInner("<a href='"+data.url+"'></a>");
				
				expandPanel();
			
			});
			return false;
		}else{
			obj.hide().empty().append("<b>"+data.intro+"</b> "+wbr(data.title,6)).wrapInner("<a href='"+data.url+"'></a>");
			expandPanel();
		}
	}

	
	};
	
	
	// Define some settings
	$.fn.BBCHeadline.defaults = {
	  numberOfitems:1,
	  url:'',
	  intro:defaultMessage
	};
	

})(jQuery);




function wbr(str, num) { 

	return str;
	
	// Could be used to break up the string...
	/*
	var tmp = str.split(" ");
	for(i in tmp){
		var word = tmp[i];
		if(word.length > num){
			var z = 0;
			var tword = "<span class='wbr'>";
			while(z < word.length){
				if(z+num > word.length){
					tword += word.slice(z)+"</span>";
				}else{
					tword += "</span><span class='wbr'>"+word.slice(z,z+num) + "<wbr>";
				}
				z+=num;
			}
			tmp[i] = tword;
		}
	}
	tmp = tmp.join(" ");
	//$.log(tmp);
	return tmp;
	*/
}





function formatHeadline(obj, data){

		sLoad = true;
		if(data.img){
			obj.image(data.img,function(){
				obj.hide().append(wbr(data.title,6)).wrapInner("<a href='"+data.url+"'></a>").find("img").addClass("headline-image");
				if(ie==6){
					//obj.show();
					expandPanel();
				}else{
					//obj.fadeIn("fast");
					expandPanel();
				}
				
			},function(){
			
				$.error("No Image available with this news story");
				obj.hide().empty().append("<b>"+data.intro+"</b> "+wbr(data.title,6)).wrapInner("<a href='"+data.url+"'></a>");
				
				expandPanel();
			
			});
			return false;
		}else{
			obj.hide().empty().append("<b>"+data.intro+"</b> "+wbr(data.title,6)).wrapInner("<a href='"+data.url+"'></a>");
			expandPanel();
		}
		
}


$.fn.image = function(src, f, e){
	var i = new Image();
	var t = $(this);
	imgload = $(i).load(function(){
		var th = $(this);
		t.hide();
		// Fade would fade out the loading icon, but removed for speed
		//t.fadeOut("fast",function(){
			t.html(th);
			f();
		//});
		
	}).bind("error",function(){ e(); $.log("Error loading image: "+src); }).attr('src', src);
}


