// functions to aid the loading and display of remote content using AJAX


// extend jQueries filters
$.expr[":"].startsWith = function(el, i, m) {
var search = m[3];
if (!search) return false;
return eval("/^[/s]*" + search + "/i").test($(el).text());
};

$.expr[":"].containsNoCase = function(el, i, m) {
var search = m[3];
if (!search) return false;
return eval("/" + search + "/i").test($(el).text());
};

$.expr[":"].containsAlpha = function(el, i, m) {
var search = m[3];
if (!search) return false;
// want to match alpha numerics in string only incase puncuation or extra space has been added
search = search.replace(/[^a-z1-9]+/gi,"");
return eval("/" + search + "/i").test($(el).text().replace(/[^a-z1-9]+/gi,""));
};

// escape special chars within string for use within regEx functions
function RegEscape(val){
	val = val.replace(/([-?*+$^|{}[\]():.\/])/g,"\\$1")
	val = val.replace(/(\\\\)([-?*+$^|{}[\]():.\/])/g,"\\$2")
	return val;
}

// DO INSTR!!!!!
function AlphaMatch(a,b){
	ShowDebug("IN AlphaMatch a = " + a + " b = " + b)
	var r=false;
	if(a && b){
		a = a.replace(/[^a-z1-9]+/gi,"")
		b = b.replace(/[^a-z1-9]+/gi,"")
		ShowDebug("does '" + a + "' == '" + b + "' ??");
		if(a.length>0 && b.length>0 && a==b) r=true;
	}
	return r;
}

// code for showing a loading animation during content load
Cursor = {
	LoaderImgID : "newsloader",

	LoaderSrc : "/images/ajax-loader.gif",

	LoaderImg : null,

	CreateImage : function(){
		this.LoaderImg = _d.createElement("IMG");
		S.setAttributes(this.LoaderImg,{id:this.LoaderImgID,src:this.LoaderSrc});
		S.setStyles(this.LoaderImg,{position:"absolute",visibility:"hidden",display:"block"});
		S.getBody().appendChild(this.LoaderImg);		
	},

	Show : function(e){		
		var x=e.pageX,y=e.pageY;
		
		if(!this.LoaderImg){
			this.CreateImage();
		}		
		
		var img = G("newsloader");
		S.setStyles(img,{left:x+"px",top:y+"px",visibility:"visible"});
		
	},

	Hide : function(){		
		G(this.LoaderImgID).style.visibility = "hidden";
	}
}


function Ripper(){

	this.Proxy = "/ajaxproxy.asp"; // location of proxy to handle cross domain requests

	this.ReqType = "GET";  // request type GET or POST

	this.Timeout = 10; // timeout in seconds to wait before aborting request or appearance of

	this.Timer;

	this.ShowingLoader = false;

	this.URL = "";

	this.Data = "";

	this.CallbackFunc;

	this.LoadContent = function(event,url,data,callback){
		
		var self = this;

		ShowDebug("in LoadContent url="+url + " data="+data+ " callback="+callback);

		// show loading icon
		Cursor.Show(GetEvent(event));
		this.ShowingLoader = true;

		setTimeout(function(){self.KillLoader()},self.Timeout*1000);

		// make sure callback is set if no data is passed in
		if(!callback && S.isFunction(data)){
			callback = data;
			data = null;
		}

		ShowDebug("callback = " + callback);
		ShowDebug("data = " + data);

		// if url we want to load isn't on our domain then set proxy flag
		var urlparts = /^([a-z]+:)?\/\/([^\/?#]+)/.exec( url );
		
		if ( urlparts && ( urlparts[1] && urlparts[1] != location.protocol || urlparts[2] != location.host )){
			ShowDebug("url is cross domain")
			var ud = "u="+ url;
			// pass the url we want as a param to our proxy
			data = (S.isEmpty(data)) ? ud : ud + "&" + data;

			// the actual url to call is our proxy
			url = this.Proxy;

			// have to POST to proxy
			this.ReqType = "POST"; 

			ShowDebug("use POST through PROXY");
		}

		ShowDebug("url = " +url);
		ShowDebug("data = " + data);

		this.URL = url;
		this.Data = data;

		var callbackfunc;

		if(S.isFunction(callback)){
			this.CallbackFunc = function(result){ ShowDebug("in CallbackFunc"); callback(result); ShowDebug("call KillLoader");self.KillLoader();}
		}else{
			this.CallbackFunc = KillLoader;
		}

		// call ajax loader
		this.AjaxLoader();

		ShowDebug("return");
	}
	
	this.KillLoader = function(){
		var self = this;
		ShowDebug("in KillLoader");
		
		if(	self.ShowingLoader ){
			ShowDebug("hide image - kill timer");
			self.ShowingLoader = false;
			// hide loading image
			Cursor.Hide()
		}
		clearInterval(self.Timer);		
	}

	this.AjaxLoader = function(){

		ShowDebug("in AjaxLoader");

		ShowDebug("this.URL = " + this.URL)
		ShowDebug("this.Data = " + this.Data)
		ShowDebug("this.ReqType = " + this.ReqType)
		ShowDebug("this.CallbackFunc = " + this.CallbackFunc)

		$.ajax({
			type: this.ReqType,
			url: this.URL,			
			//url:"/scores/england_082009.htm",
			data: this.Data,
			success: this.CallbackFunc			
		});
	}

	this.IframeLoader = function(){

	}
}


// Ripper functions for accessing content from DOM

// returns DOM nodes by looking for a selector, pass in multiples and will return first one found
function getContentBySelector(dom,lk,t){
	ShowDebug("IN getContent");
	var fp,sel;
	if(dom && lk){
		for(var x=0;x<lk.length;x++){
			sel = lk[x];
			ShowDebug("try selector = " + sel);
			fp = jQuery(dom).find(sel);
			if(fp.length>0){
				ShowDebug("found with " + sel +" length = " + fp.length);				
				if(AlphaMatch(t,fp.html())){
					ShowDebug("this matches our search term look for another index")
				}
				break;
			}
		}
	}
	if(fp && fp.length>0){
		ShowDebug("We found content!! html = " + fp.html());
	}
	return fp;
}

// clean up HTML
function cleanupHTML(r){
	ShowDebug("IN cleanupHTML = " + r);

	r = r.replace(/<script.*?>(.|\s)+?<\/script>/gi,""); //remove script tags							
	r = r.replace(/<noscript>(.|\s)*?<\/noscript>/gi,"");//remove noscript				
	r = r.replace(/<style.*?>(.|\s)+?<\/style>/gi,""); //remove style tags			
	r = r.replace(/<object.*?>(.|\s)+?<\/object>/gi,""); //remove object tags			
	r = r.replace(/<embed.*?>(.|\s)+?(<\/embed>|\/?>)/gi,""); //remove embed tags	
	r = r.replace(/<!--(.|\s)+?-->/g,"");//remove comments				
	r = r.replace(/<p>\s*&nbsp;\s*<\/p>/gi,"");//remove empty paragraphs
	r = r.replace(/<p>\s*<\/p>/gi,"");//remove empty paragraphs		
	// use ? round quotes to handle IE which can sometimes remove them from source code!
	r = r.replace(/<div class="?[-a-z1-9 ]+"?>\s*<\/div>/gi,"");//remove empty DIVs

	return r;
}

// remove styling
function cleanStyling(r){
	ShowDebug("IN cleanStyling = " + r);

	if(!S.isEmpty(r)){
		r = r.replace(/(<\w+.* )(style=['"].+?['"])/gi,"$1");

		ShowDebug("after style = " + r)

		r = r.replace(/(<\w+.* )(class=['"].+?['"])/gi,"$1");

		ShowDebug("after class = " + r)

		r = r.replace(/<\/?font.*?>/gi,"");
	}else{
		r = ""
	}
	ShowDebug("after font = " + r)

	return r;
}

// remove excess <br> tags
// m = min no of <br> tags to allow e.g 2 will leave 2 of X
function removeBRS(r,m){
	var m = m || 1; // default to one
	if(!S.isEmpty(r)){	
		var rg = '((\\s?<br\\s?\\/?>\\s?){0,'+m+'})(\\s*<br\\s?\\/?>)+';
		var re = new RegExp(rg,'gi');
		r = r.replace(re,"$1");
	}else{
		r = "";
	}

	return r;
}

// Changes relative URLs to use current domain. IE6 does this
function changeURL(r){
	ShowDebug("IN changeURL " + r);

	// get the current domain
	var cd = getDomain(document.location.href);				
	//format url for use in regEx
	cd = cd.replace(/\//g,"\\/").replace(/\./g,"\\.").replace(/\:/,"\\:");				
	var re = '(<img.+?src=\")('+cd+')(\\/.+?\".*?\\/?>)';				
	var reg = new RegExp(re,"gi");				
	r = r.replace(reg,"$1"+bs+"$3");				

	return r;
}

// changes relative URIs in images and links to use the base href supplied
function changeABSURL(r,bs){
	ShowDebug("IN changeABSURL = " + r);
	// make relative paths absolute
	r = r.replace(/(<img.+?src=")(\/.+?".*?\/?>)/gi,"$1"+bs+"$2"); //make relative URIs on images absolute			
	r = r.replace(/(<a.+?href=")(\/.+?".*?>)/gi,"$1"+bs+"$2"); //make relative URIs on links absolute			
	return r;
}


// adds missing paragraph tags around text
function addMissingPara(r){	
	ShowDebug("IN addMissingPara = " + r);
	// add missing p tags
	r = r.replace(/(<\/p>\s*)(\w+[\W\w]+?)(\s*<p>)/gi,"$1<p>$2</p>$3");
	return r;
}


function getDomain(str)
{
	ShowDebug("IN getDomain = " + str);

	if(S.isEmpty(str)) return "";

	str = str.toLowerCase();

	// replace :// with placeholder to allow us to search for single /
	str = str.replace(/^(ftp|https?)(:\/\/)/,"$1##CL##");

	ShowDebug("str = " + str);

	// apart from protocol is there a slash if not use whole url
	var i = str.indexOf("/");
	if(i == -1){
		str = str.replace(/##CL##/,"://");
	}else{
	// take up to the first /
		str = str.substring(0, i).replace(/##CL##/,"://");
	}

	ShowDebug("return " + str)
	return str;

}