
DOM(function(){
	//D.debug=true;
	ShowDebug("IN DOM LOAD DID RSS LOAD");
	// check whether we are on a league page that should show related news
	var league = G('League') && G('LatestNews');
	var home = G('HomeNews') && true;
	var trans = !V.isEnglish;	
	// if on league page but RSS hasn't loaded then go for a JS load
	if(league || home){
		ShowDebug("on league or home page");
		var rss = G('RSSList');
		if(!rss || (rss && home && trans)){			
			ShowDebug("NO RSS OR TRANSLATE");
			//console.log("where is debug? D.debug = " + D.debug)		
			
			// if we already have an RSS then clear contents
			if(rss){
				if ( rss.hasChildNodes() ){
					while ( rss.childNodes.length >= 1 ){
						rss.removeChild( rss.firstChild );       
					} 
				}				
			}
			
			// create UL
			var ul=_d.createElement("UL");
			var n = (home) ? "latestNews" : "leagueNews";
			ul.setAttribute("id",n);
			if(home){
				G('HomeNews').appendChild(ul);

				var news = new H.Feeder();
				news.FeedType = "news";
				news.ShowSnippet = true;
				news.OutputNo = 6;
				ShowDebug("just set FeedType to news check  " + news.FeedType);
				news.getFeedOutputElement = n; // where to output results				
				news.AttachContentLoader=true;
				// loop through main feeds adding them	
				for(var x=0,l=H.MainNewsFeeds.length;x<l;x++){					
					news.loadFeed(H.MainNewsFeeds[x]);
				}
				
			}else{
				G('LatestNews').appendChild(ul);
				// load from google
				var news = new H.Feeder();
				news.FeedType = "news";
				//news.searchQuery = $('h1').html();
				
				var cn = document.location.href.replace(/^.+?\/([^\/]+)$/g,"$1");
				var lg = document.title.replace(/ \- Hattrick Heaven/,"");			
				//var sq = "Brazil football latest scores";
				news.searchQuery = "Latest Football soccer news from " + cn + " " + lg;
			
				ShowDebug("search query = " + news.searchQuery);
				news.ShowSnippet = true;
				news.ItemsPerFeed = 10; //set high as we want to return quality
				news.OutputNo = 30; //set high as we are doing a keyword search
				news.KeywordType = "OR";
				news.Keywords = "goal,soccer,football,"+cn;			
				ShowDebug("just set FeedType to news check  " + news.FeedType);
				news.getFeedOutputElement = "leagueNews"; // where to output results
				news.AttachContentLoader = true;// add my content loader function
				news.findFeeds(); // run news			
				ShowDebug("let google run feeds");
			}
			
			//D.debug = false;
		}
	}
	//D.debug=false;
})



function getNewsContent(dt,txt,header) {
	ShowDebug("getNewsContent by looking for = " + txt + " OR " + header);
	var sel = [ "p.first","p.ss-text-bold", "div.articleBody","div.sp-story > p","div.storyindexabstract"];
	fp = getContentBySelector(dt,sel,txt);
	
	var g = (fp && fp.length>0) ? true : false;
	
	ShowDebug("g = " + g)
	
	if(!g && !S.isEmpty(txt)){
		ShowDebug("couldnt find so do a contains search within P");

		// make sure any guff that is in our snippet but won't be in the article is removed to aid a the search
		// e.g remove any trailing ... at the end as these wont be in the article so our lookup won't match
		txt = txt.replace(/[\s\.:;>]+$/,"");
		ShowDebug("actual text to search for is " + txt + " ONCE non alpha removed it will be = " +  txt.replace(/[^a-z1-9]+/gi,""));
	
		// look for our textual snippet using a custom filter that removes puncuation, spaces and other non-alphanumeric chars
		var sel = [ "p:containsAlpha("+txt+")",  ":containsAlpha("+txt+")"];
		fp = getContentBySelector(dt,sel,txt);
		g = (fp && fp.length>0) ? true : false;
	}

	ShowDebug("g = " + g);

	// if no luck try for the header instead
	if(!g && !S.isEmpty(header)){
		ShowDebug("try for header instead");
		// remove any trailing full stops or space
		header = header.replace(/[\s\.\:;>]+$/,"");
		
		// look for a header using custom filter and checking the main 3 heading types h1,h2,h3
		var sel=[ "h1:contains("+header+")","h2:contains("+header+")","h3:contains("+header+")"];
		fp = getContentBySelector(dt,sel,header);
		if(fp && fp.length>0){
			ShowDebug("found!");
			// dont want to return the header but get the next P
			fp = fp.siblings("p");			
		}
	}

	ShowDebug("fp = " + fp + " - " + fp.length);
	//ShowDebug("return " + G(fp));
	return fp;
}

function reformatData(dt, n, bs, ti) {
	//D.debug = true;
	ShowDebug("in reformatData baseURL = " + bs + ", title = " + ti);

	//ShowDebug("orig content = " +dt);
	var h,r = n || "";
	if (!S.isEmpty(dt)) {
		
		// extract html,head and body tags so we just have the main content
		dt = (dt.match(/(<body.*?>)((?:.|\s)+?)(<\/body>)/i) || [])[2];
		// get array of paragraphs holding main story content
		var fp = getNewsContent(dt, n, ti);
		if(fp.length>0){
			ShowDebug("we have " + fp.length + " nodes to look")
			// one node
			if(fp.length==1){
				h = S.Trim(fp.html());
				ShowDebug("content back from getNewsContent = " + h);
				// only wrap if it was found outside a p
				if(!/^<p>/.test(h)){
					h = "<p>" + h + "</p>";
				}
			}else{
				var al=cn=ll="";
				for(var x=0;x<fp.length;x++){
					al = fp[x].innerHTML;
					ShowDebug("content from node " + x + " is = " + al);
					if(cn!=""){						
						ShowDebug("check with AlphaMatch that " + al + " is not " + ll);
						if(AlphaMatch(al,ll)){							
							al = ""; //reset so its not added
						}
					}
					if(al!=""){
						if(!/^<p>/.test(al)){
							cn += "<p>"+al+"</p>";
						}else{
							cn += al;
						}
					}
					//set last one
					ll = al;
				}
				h = cn;
			}

			
			ShowDebug("h = " + h);
			
			ShowDebug("look at siblng");
			var o = h;

			fp.siblings("p").each(
				function() {
					ShowDebug("SIBLING = " + this.tagName + " - " + this.innerHTML);
					h += "<p>" + this.innerHTML + "</p>";
				}
			)
			
			if(o==h){
				ShowDebug("nothing added try to fix");
				
				var i = jQuery(dt).find("div.pageLayout").html()
				//ShowDebug("from div.pageLayout > span#intelliTXT ===  "+ i);
				if(i){h+=i}
			}
			r = h;   
			
		}	
		if(!S.isEmpty(r)){
			
			//ShowDebug("now reformat for our viewing");
			//ShowDebug("b4 reformat = " + r);
			// make sure we have no guff in our string		
			r = cleanupHTML(r)			
			r = r.replace(/<div class="?clubBold"?>(\s|.)+?<\/div>/gi,""); //remove guff
			
			ShowDebug("current content = " + r);
			// site specific guff
			if(/Soccer365/i.test(bs)){
				ShowDebug("SOCCER NET SPECIFIC");				
				// remove comments
				c = $(dt).find("div.comments").html();
				//ShowDebug("comment html = " + c);
				//ShowDebug("escaped = " + RegEscape(c))
				var re = new RegExp(RegEscape(c));
				r = r.replace(re,"");
				ShowDebug("after comment html removed = " + r);
				r = r.replace(/<div class=\"?gradientHeader450\">(\s|.)+?<\/div>/gi,""); //remove header
				r = r.replace(/<div class=\"?greyContent470\">(\s|.)+?<\/div>/gi,""); //remove header
				r = r.replace(/<div class=\"?user_links clearfix\" id=\"?\w.+?>(\s|.)+?<\/div>/gi,""); //remove link options
				r = r.replace(/<div class=\"?dummy\" style=\"?\w.+?>(\s|.)+?<\/div>/gi,""); //remove link options
				r = r.replace(/<div class=\"?storyindextitle\">(\s|.)+?<\/div>/gi,"");
				r = r.replace(/<div class=\"?storyindexdate\">(\s|.)+?<\/div>/gi,"");
				r = r.replace(/<div class=\"?storybox\">(\s|.)+?<\/div>/gi,"");
				r = r.replace(/<div class=\"?comments\">(\s|.)+?<\/div>/gi,"");
				r = r.replace(/<a href=\"http:\/\/store.+?\"><font.*>.+?<\/font><\/a>/gi,"");//remove advert
				r = r.replace(/(<\/div>|<div.*?>)/gi,"");
			
			}		
			
			// do this here as we remove any remaining class tags
			r = cleanStyling(r);
			r = removeBRS(r,2);

			// for IE6 that will replace relative URLs with the current domain we need to replace our domain with their base URL
			if(S.Browser.ie && S.Browser.version<=6){								
				r = changeURL(r)
			}

			// make relative paths absolute
			r = changeABSURL(r,bs)
			
			// add missing P tags
			r = addMissingPara(r);

			// do site/feed specific cleanups
			r = r.replace(/<b>Other links of interest\:<\/b><br>\s*(<a href.+<\/a><br>\s*)+/gi,"");
		}
	}
	//ShowDebug("RETURN FROM reformatData = " + (r||n));
	return r||n;
}

var newsCache = {};
function newsItem(a,s,x){
	this.article = a||"";
	this.snippet = s||"";
	this.mode = x||"snippet";
}

DOM(function() {
	//D.debug = true;
	//ShowDebug("IN DOM Onload Bind Click events");
	$(".newsLinks > li > a").bind("click", ContentLoader);
}); //END DOMREADY



function ContentLoader(event,el,content) {	
	//D.debug = true;
	ShowDebug("CLICK EVENT FIRED! LOAD REMOTE URL CONTENT");
	//ShowDebug("stop default event = " + event + " - " + el + " - " + content);
	StopEvent(event);
	//ShowDebug("should have been stopped")
	if(!el){
		el = (event.target.tagName.toUpperCase=="A") ? event.target : this;
	}
	// get the URL for the main article
	
	var a = $(el); //$(event.target); //this seems to get lost on the way
	var lnk = a.html();
	var t, nc, u = a.attr("href");

	ShowDebug("check cache["+u+"] = " + newsCache[u]);
	// create cache
	if (!newsCache[u]) {
		ShowDebug("create cache for url = " + u)
		nc = new newsItem();
		newsCache[u] = nc;
	} else {
		nc = newsCache[u];
		ShowDebug("got existing cache object lets look")
	}
	ShowDebug("current mode = " + nc.mode);

	if (nc.mode == "snippet") {		
		var p = a.next("p"); //get current paragraph
	} else {
		ShowDebug("remove close link");
		// remove guff	
		a.html(lnk.replace(/(&nbsp;|\s){2,2}<strong>\[ Click link to close \]<\/strong>/i,""));
		var p = a.next("div"); //get current div which we change from a P when showing article
	}
	//check current status of text is it the snippet or full article
	if (nc.mode == "article") {		
		var snip = nc.snippet;
		
		// swap div with a p and remove article replacing it with snippet
		p.replaceWith("<p class='snippet'>" + snip + "</p>");
		// toggle class and remove article
		
		nc.mode = "snippet"; //showing snippet again               
	} else {	
		
		// do we already have full article in cache or passed in?
		var ar = nc.article || content;
		ShowDebug("article from cache/passed in = " + ar);
		snip = p.html(); //get current snippet html
		//store in cache
		nc.snippet = snip;

		if (S.isEmpty(ar)) {
			//D.debug=true;
			var news = new Ripper();
			ShowDebug("got ripper object u = " + u);
			news.LoadContent(event,u,function(result){
				
					ShowDebug("IN SUCCESS url = " + u + " - " + this.url)

					// call function to look for extra content from main article			
					var r = reformatData(result, snip, getDomain(u),lnk);
					//ShowDebug("got reformated article back = " + r);
					// add link to full article just in case we cannot get contents so user still can				
					r += "<p style='text-align:right;margin-bottom:7px;margin-top:5px;'><a href='"+u+"' target='_blank' title='" + nc.snippet + "'>[view original article]</a></p>";
				
					$(a).html(lnk + "&nbsp;&nbsp;<strong>[ Click link to close ]</strong>");
					// replace current paragraph with a DIV and show article content				
					var nr = "<div class='article'>" + r + "</div>";
					//ShowDebug("put inside our div class=article = " + nr);
					p.replaceWith(nr);
					nc.article = nr;
					//D.debug=false;
			})
			news=null;			
		} else {
			$(a).html(lnk + "&nbsp;&nbsp;<strong>[ Click link to close ]</strong>");
			p.replaceWith("<div class='article'>" + ar + "</div>");
			nc.article = ar;
		}

	nc.mode = "article"; //showing article
	}

	return;

}