var RPOST;
if (!RPOST) RPOST = {};
RPOST.applet = 
{
	  ATL: null
	, ricegrainsRegistered: false
	, bookieChooser:null
	, marketList: []	
	, ricegrainApplet: null
	, maxATLRetry:RPOST.maxSyncRetries
	, ricegrainsToLookFor:[]
	
	, setATL: function(atl)
	{
		RPOST.applet.ATL = atl;  
		if (this.ricegrainsRegistered) 
		{
			this.loadRicegrainApplet();
		}
	}
	
	, registerRicegrain: function(params)
	{
		this.ricegrainsToLookFor.push(params);
		this.ricegrainsRegistered = true;
		if (this.ATL)
			this.loadRicegrainApplet();
	}
	
	, loadRicegrainApplet: function()
	{
		if (this.ricegrainApplet !== null) return;
		var pb= new RPOST.applet.MarketGroup(
		{
			renderType:'renderAsRicegrains', 
			instanceName:'RPOST.applet.ricegrainApplet', 
			marketIds: 'multi',  
			format:'frac', 
			mustLogin:'N', 
			skin: RPOST.appletRoot+'Styles'
		});
		RPOST.applet.ricegrainApplet = pb;
		if (pb && !pb.bust)
			pb.start();					
		this.ATL.suggestRicegrainSearch();	
	}
	
	, createPriceAppletDataRender: function(params)
	{
		var _this = this, idx;
		try { if (RPOST.applet.ATL === null )
			{
				if (this.maxATLRetry-- > 0)
					{ setTimeout(function() {_this.createPriceAppletDataRender(params);}, 10); return params.targetId;  }
				else {  return; }
			}
		} catch (e) {}
		idx = this.marketList.length;
		params.renderType = "renderAsData";
		params.instanceName = "RPOST.applet.marketList["+idx+"]";
		params.instance= new RPOST.applet.MarketGroup(params);
		params.instance.start();
		this.marketList.push(params);
		return params.targetId; 
	}
	
	, PriceboxClass : "init"
	, createPriceAppletBoxRender: function(params) // { marketIds, 
	{
		var _this = this, idx;
		
		try { if (RPOST.applet.ATL === null)
			{
				if (this.maxATLRetry-- > 0) { setTimeout(function() {_this.createPriceAppletBoxRender(params);}, 10); return params.targetId; }
				else	 {  return; }
			}
		} catch (e) {}
		idx = this.marketList.length;
		params.renderType = "renderAsBox";
		params.instanceName="RPOST.applet.marketList["+idx+"]";
		params.skin = RPOST.appletRoot+'/images/glyph_vert';

		if (RPOST.applet.PriceboxClass == "init")
		{
			this.PriceboxClass = false;			
			this.toolkit.includeScript(RPOST.appletRoot+'/Applets/PriceboxClass.js');
		}
		if (!RPOST.applet.PriceboxClass)
		{
			this.marketList.push(params);
		}
		else // fully loaded; just ask for a new one
		{
			idx = this.marketList.length;
			params.instance = new RPOST.applet.MarketGroup(params);
			params.instance.start();
			this.marketList.push(params);
		}
		return params.targetId;		
	}
	
	
	, commentariesList: []
	, CommentaryClass: "init"
	, createCommentary: function(params) // {marketId, w, h, dir, max, type, targetId } 
	{
		var _this = this;
		
		try { if (RPOST.applet.ATL === null)
			{
				if (this.maxATLRetry-- > 0) { setTimeout(function() {_this.createCommentary(params);}, 10); return params.targetId; }
				else	 {  return; }
			}
		} catch (e) {}
		if (params.style)
			this.toolkit.includeStyle(RPOST.appletRoot+"/Styles/"+params.style);
		if (RPOST.applet.CommentaryClass == "init")
		{
			this.CommentaryClass = false;
			this.toolkit.includeScript(RPOST.appletRoot+'/Applets/CommentaryClass.js');
		}
		if (!RPOST.applet.CommentaryClass)
		{
			this.commentariesList.push(params);
		}
		else // fully loaded; just ask for a new one
		{
			params.instance = new this.CommentaryClass(params);
			this.commentariesList.push(params);
		}
		return params.targetId;
	}

	, generalMessagesList: []
	, GeneralMessageClass: "init"
	, createGeneralMessage: function(params) // {marketId, dir, max, targetId } 
	{
		var _this = this;
		try { if (RPOST.applet.ATL === null)
			{
				if (this.maxATLRetry-- > 0) { setTimeout(function() {_this.createGeneralMessage(params);}, 10); return params.targetId; }
				else	 {  return; }
			}
		} catch (e) {}
		if (RPOST.applet.GeneralMessageClass == "init")
		{
			this.GeneralMessageClass = false;
			this.toolkit.includeScript(RPOST.appletRoot+'/Applets/CommentaryClass.js');
		}
		if (!RPOST.applet.GeneralMessageClass)
		{
			this.generalMessagesList.push(params);
		}
		else // fully loaded; just ask for a new one
		{
			params.instance = new this.GeneralMessageClass(params);
			this.generalMessagesList.push(params);
		}
		return params.targetId;
	}
	
	, destroyApplet: function(id)
	{
		var ap = null, i;
		for (i in this.commentariesList)		
			if (this.commentariesList[i].targetId == id)
				{ ap = this.commentariesList[i]; this.commentariesList.splice(i, 1);break; } 
			
		if (!ap)	
			for (i in this.generalMessagesList)
				if (this.generalMessagesList[i].targetId == id)
					{ ap = this.generalMessagesList[i]; this.generalMessagesList.splice(i, 1); break; } 
				
		if (!ap)	
			for (i in this.MarketList)
				if (this.MarketList[i].targetId == id)
					{ ap = this.MarketList[i]; this.MarketList.splice(i, 1); break; } 
			
		if (!ap) return;
		if (typeof ap.instance.destroy == "function")		
			ap.instance.destroy();
	}

	
	
	
// --------------------------- Tools namespace
	, toolkit: 
	{
		   myURL: ""	  
		, elements: []  		  
		, debug: RPOST.debug		
		, setSubdomain: RPOST.setSubdomain
		, includes: []

		, includeScript : function(script_filename)
		{
			var html_doc, js;
			
			if (this.includes[script_filename]) return; 
			this.includes[script_filename] = true;
			html_doc = document.getElementsByTagName('head').item(0);
			js = document.createElement('script');
			js.setAttribute('language', 'javascript');
			js.setAttribute('type', 'text/javascript');
			js.setAttribute('src', script_filename);
			html_doc.appendChild(js);
		}

		, includeStyle : function(style_filename)
		{
			var html_doc, css;
		
			if (this.includes[style_filename]) return; 
			this.includes[style_filename] = true;
			html_doc = document.getElementsByTagName('head').item(0);
			css = document.createElement('link');
			css.setAttribute('rel', 'stylesheet');
			css.setAttribute('type', 'text/css');
			css.setAttribute('href', style_filename+".css");
			html_doc.appendChild(css);
		}
		
		, loadATL : function()
		{
			var html_doc, iframe, bc;
		
			html_doc = document.getElementsByTagName('body').item(0);
			iframe = document.createElement('iframe');
			iframe.style.position = "absolute";
			iframe.style.visibility = "hidden";
			iframe.style.display = "none";
			iframe.setAttribute('src', RPOST.appletRoot+'/AppletTransportLayer.html');
			html_doc.appendChild(iframe);
			this.includeStyle(RPOST.appletRoot+"/Styles/bet_now_1");
			bc = document.createElement('span');
			bc.className = "bkchooser";
			html_doc.appendChild(bc);
			RPOST.applet.bookieChooser = bc;
		}

		, getElement : function(name, nocache)
		{
			var el;
			
			if (nocache) return document.getElementById(name);
			el = this.elements[name];
			if (!el) el = this.elements[name] = document.getElementById(name);
			return el;
		}

		
		, getElementsByName: function(doc, tag, nameval)
		{
			var i, el, els, len, out;
			
			if (!RPOST.isIE()) return doc.getElementsByName(nameval);
			els = doc.getElementsByTagName(tag);
			len = els.length;
			out = [];
			for (i=0; i<len; i++)
			{
				el = els[i];
				if (!el.getAttribute) continue;
				if (el.getAttribute("name") == nameval) out.push(el);
			}
			return out;
		}
		
		, getCookie: function(name)
		{
			var sRE = "(?:; )?" + name + "=([^;]*);?";
			var oRE = new RegExp(sRE);
			if(oRE.test(document.cookie))
			{
				if(RPOST.isSafari()) { return unescape(RegExp["$1"]); }
				else { return decodeURIComponent(RegExp["$1"]); }
			}
			else return "";
		}

//		, setImageBase: function(base)
//		{
//			this.imageBase = base;
//		}
//		
//		, getImage: function(name)
//		{
//			return this.imageBase + "/" + name;
//		}
		
		, getWindowSize: function(doc)
		{
			var myWidth = 0, myHeight = 0;

			if( typeof( doc.window.innerWidth ) == 'number' )
			{
				//Non-IE
				myWidth = doc.window.innerWidth;
				myHeight = doc.window.innerHeight;
			} else if( doc.document.documentElement && ( doc.document.documentElement.clientWidth || doc.document.documentElement.clientHeight ) )
			{
				//IE 6+ in 'standards compliant mode'
				myWidth = doc.document.documentElement.clientWidth;
				myHeight = doc.document.documentElement.clientHeight;
			} else if( doc.document.body && ( doc.document.body.clientWidth || doc.document.body.clientHeight ) )
			{
				//IE 4 compatible
				myWidth = doc.document.body.clientWidth;
				myHeight = doc.document.body.clientHeight;
			}
			return {W:myWidth, H:myHeight};
		}
		
		, findPos: function(obj)
		{
			var curleft=0, curtop=0;

			if (obj.offsetParent)
			{
				do {
						curleft += obj.offsetLeft;
						curtop += obj.offsetTop;
				} while ((obj = obj.offsetParent));
			}
			return {X:curleft,Y:curtop};
		}
		
		, getTransparencyStyle: function()
		{
			if (!RPOST.isIE())
				return "opacity:1;";
			else
				return "background-color:transparent;";
		}				
	} // end of RPOST.toolkit

	
	
// A market
	, MarketClass: function(params) // holder, uid, isFirst
	{		
		var _NS = RPOST.applet.MarketClass;
		this.debug = params.holder.toolkit.debug;
		this.toolkit = params.holder.toolkit;
	
		if (!_NS.prototype._setup_) // build class prototype 1st time only
		{
			_NS.prototype.classname = "MarketClass";
			
			_NS.prototype.getProperties = function() 
			{
				if (typeof(this.getPropertiesImpl) == "function") this.getPropertiesImpl();
			};
			_NS.prototype.getStatusbarHTML = function() 
			{
				if (typeof(this.getStatusbarHTMLImpl) == "function") return this.getStatusbarHTMLImpl();
				return "";
			};

			_NS.prototype.cachedInnerHtml = function(el, idx, data)
			{
				if (el && el !== null)
				{
					if (this.dataStore[idx] !== data)
					{
						el.innerHTML = data;
						this.dataStore[idx] = data;
					}
				}
			};

			_NS.prototype.getTitle = function()
			{
				var txt, o;
				
				if (this._title.text != ""){	return this._title.text; }
				txt = "no data yet";
				for (o in this.outcomes)
				{
					txt += this.outcomes[o]._name+" ";
				}
				return txt;
			};

			_NS.prototype.registerDataConsumers = function()
			{
				this.holder.dataObject.registerConsumer(this.outcomeConsumer);
				this.holder.dataObject.registerConsumer(this.priceConsumer);
			};

			_NS.prototype.start = function()
			{
				this.checkSuspend();
				this.started = true;
			};

			_NS.prototype.stop = function()
			{
				this.holder.dataObject.unregisterConsumer(this.outcomeConsumer);
				this.holder.dataObject.unregisterConsumer(this.priceConsumer);

				clearTimeout(this.suspendTid);
				clearTimeout(this.checkTid);
			};

			_NS.prototype.getBetslipURL = function(outcomeIdx, bookieIdx)
			{
				var sport = this.holder.sport, i, bookie, price, URL, den, num, type;

				if (this.ricegrainPrices !== null)
				{
					for (i in this.ricegrainPrices)
					{
						if (this.ricegrainPrices[i].outcomeID != outcomeIdx) continue;						
						sport = this.ricegrainPrices[i].sport;
						break;
					}
				}
				if (this.holder.getUserMD5() == "") // not logged in
				{
					if (this.holder.params.mustLogin == "Y" ||
						(this.holder.params.mustLogin != "N" && sport == "Horses"))
					{
						alert("Please login to the Betting Site using your Racing Post\nusername and password prior to striking your bet");
						return "";
					}
				}
				bookie = this.holder.bookieData[bookieIdx];
				price = this._outcomes[outcomeIdx]._prices[bookieIdx];
				URL = bookie._url.replace(/%a/g, bookie._affid);
				den=""; num=""; type="";
				if (price._odds[0] == "SP") { type = "S"; }
				else
				{
					type = "L";
					num = price._odds[0].slice(0, price._odds[0].indexOf('/'));
					den = price._odds[0].slice(price._odds[0].indexOf('/') + 1);
				}
				URL = URL.replace(/%n/, num);
				URL = URL.replace(/%d/, den);
				URL = URL.replace(/%t/, type);
				URL = URL.replace(/%p/, price._odds[0]);
				URL = URL.replace(/%x/, price._bookie_price);
				URL = URL.replace(/%e/, price._bookie_event);
				

				switch(bookie._name)
				{
					case "Sporting Bet":
						URL = URL.replace(/%s/, bookie._sportIDs[this.holder.params.sport]);
						URL = URL.replace(/%u/, price._bookie_outcome);
						URL = URL.replace(/%i/, this.holder.getUserMD5() == "" ? "no_MD5_cookie" : this.holder.getUserMD5());
						URL = URL.replace(/%m/, price._bookie_meeting);
						break;

					case "William Hill":
						break;

					case "Bet365":
						URL = URL.replace(/%u/, price._bookie_outcome);
						URL = URL.replace(/%i/, this.holder.getUserID() == "" ? "no_ID_cookie" : this.holder.getUserID());
						URL = URL.replace(/%m/, price._bookie_meeting);
						break;

					case "Bet Fred":
						URL = URL.replace(/%u/, price._bookie_outcome/10);
						URL = URL.replace(/%i/, this.holder.getUserMD5() == "" ? "no_MD5_cookie" : this.holder.getUserMD5());
						URL = URL.replace(/%m/, price._bookie_meeting);
						break;

					case "BoyleSports":
						URL = URL.replace(/%u/, price._bookie_outcome/10);
						URL = URL.replace(/%m/, price._bookie_meeting/10);
						break;
						
					case "Stan James":
						URL = URL.replace(/%u/, price._bookie_outcome/10);
						URL = URL.replace(/%m/, price._bookie_meeting);
						break;
						
					default:
						URL = URL.replace(/%u/, price._bookie_outcome);
						URL = URL.replace(/%m/, price._bookie_meeting);
						URL = URL.replace(/%i/, this.holder.getUserMD5() == "" ? "no_MD5_cookie" : this.holder.getUserMD5());
						break;
				}
				return URL;
			};

			_NS.prototype.getPrice = function(PoutcomeIdx, PbookieIdx)
			{
				try
				{
					return this._outcomes[PoutcomeIdx]._prices[PbookieIdx]._dec[0];
				}
				catch(e) { return "0.0"; }
			};

			_NS.prototype.H_launchBetfair = function()
			{
				if (this._betfair._show == "1")
				{
					window.open(this._betfair._URL, "", "resizable,width=" + this._betfair._W + ",height=" + this._betfair._H);
				}
				else
				{
					alert("Sorry; no Betfair page for this event");
				}
			};
			
			_NS.prototype.H_launchSpread = function()
			{
				if (this._spread._show == "1")
				{
					window.open(this._spread._URL, "", "resizable,scrollbars,width=" + this._spread._W + ",height=" + this._spread._H);
				}
				else
				{
					alert("Sorry; no Spread Betting page for this event");
				}

			};
			
			_NS.prototype.hasTitle = function() { return (this._title._show == '1' && this._title._text.length > 0) ;};
			_NS.prototype.hasSpread = function() { return (this._spread._show == '1' && this._spread._URL.length > 0); };
			_NS.prototype.hasBetfair = function() { return (this._betfair._show == '1' && this._betfair._URL.length > 0); };
			_NS.prototype.outcomesToShow = function()
			{
				if (this.max_shown == 0) { return this.outcomeCount; }
				if (this.outcomeCount >= this.max_shown) { return this.max_shown; }
				return this.outcomeCount;
			};

			_NS.prototype.loadOutcomeData = function(doc)
			{
				var gotExtra=false, tmp, extra, bkuid, order, i, j, p, n, outCnt=0, data, args, outcome, ok, id, path, cnum, bindex;
				var oldOutcomes, len;

				this._gotUpdate = true;
				oldOutcomes = this._outcomes;
				this._outcomes = [];
				this._outcomes_tmp = [];
				this._extra = [];
				len = doc.length;
				this.outcomeCount = 0;
				
				for (i in this.eachway)
				{
					ok = this.eachway[i];
					for (j in ok)
					{
						ok[j].isChanged = false;
					}
				}
				for(i = 0; i < len; i++) //>
				{
					if (!doc[i])  { break; }

					data = doc[i];
					args = data.split("|");

					switch(args[0].substring(0, 1))
					{
						case 'O':
							outcome = {
								_uid:		"I" + args[0].substring(1),
								_CRid:		args[0].substring(1),
								_name:		args[1],
								_url:		args[2],
								_rat:		args[3].replace(/<h2>/g, ""),
								_orderby:	parseInt(args[4], 10),
								_image:		args[5],
								_bestPrice:	null,
								_prices:		[],
								isUnFav:	false,
								numPrices:	0
							};
							if (this.ricegrainPrices !== null)
							{
								ok=false;
								for (j in this.ricegrainPrices)
								{
									if (outcome._uid == this.ricegrainPrices[j].outcomeID) { ok = true; break; }
								}
								if (!ok) { break; }
							}
							outcome.isUnFav = args[1].toUpperCase().indexOf("UNNAMED") != -1 &&  args[1].toUpperCase().indexOf("FAVOURITE") != -1;
							if (outcome._url.length > 1)
							{
								outcome._url = outcome._url.replace("http://www.racingpost.co.uk", "@");
								cnum = outcome._url.match(/(\d+)/);
								outcome._url = this.holder.params.RPdomain+"="+(cnum? cnum[0]:"");
							}

							outcome._name = outcome._name.replace(/Iii/g, "III");
							outcome._name = outcome._name.replace(/Ii/g, "II");
							switch(outcome._name)
							{
								case "U.s.a": outcome._name = "USA"; break;
								case "Usa": outcome._name = "USA"; break;
								case "U.a.e": outcome._name = "UAE"; break;
								case "Uae": outcome._name = "UAE"; break;
							}

							if(outcome._orderby == -1)
							{
								outcome._orderby = NaN;
							}

							if (outcome._image != "")
							{
								id = outcome._image.split(".")[0].split("");
								path="/";
								for (p=id.length-1, n=0; p>=0; --p)
								{
									path += id[p]+"/";
									++n;
									if (n > 2) { break; }
								}
								outcome._image = path+outcome._image;
							}

							this._outcomes[outcome._uid] = outcome;
							this._outcomes_tmp[outCnt++] = outcome;
							if (outcome._rat == "NULL") { outcome._rat = ""; }
							if(oldOutcomes !== null && oldOutcomes[outcome._uid] !== null)
							{
								outcome._prices = oldOutcomes[outcome._uid]._prices;
							}
							break;

						case 'A':
							extra = {
								_uid : "I" + args[5],
								_active : args[0].substring(1),
								_URL : args[1],
								_text : args[2],
								_W : parseInt(args[3], 10),
								_H : parseInt(args[4], 10)
							};
							extra._URL = extra._URL.replace("http://www.racingpost.co.uk", "@");
							extra._URL = extra._URL.replace("@", this.holder.params.RPdomain);

						this._extra[extra._uid] = extra;
						gotExtra = true;
						break;

						case 'L':
							this._showExtra = args[1];
							break;

						case 'T':
							this._tv._show = args[0].substring(1);
							this._tv._URL = args[1];
							this._tv._W = parseInt(args[2], 10);
							this._tv._H = parseInt(args[3], 10);
							this._tv._text = args[4];
							break;

						case 'G':
							this._offtime._show = args[0].substring(1);
							this._offtime._text = args[1];
							break;

						case 'H':
							this._title._show = args[0].substring(1);
							this._title._text = args[1];
							this._title._text = this._title._text.replace(/<\w>/g, "");
							break;

						case 'K':
							this._spread._show = args[0].substring(1);
							this._spread._URL = "http://ad.uk.doubleclick.net/clk;110923170;17491041;q?http://www.sportingindex.com/?tpid=2604 ";
							this._spread._W = parseInt(args[2], 10);
							this._spread._H = parseInt(args[3], 10);
							break;

						case 'E':
							this._betfair._show = args[0].substring(1);
							this._betfair._URL = args[1];
							this._betfair._W = parseInt(args[2], 10);
							this._betfair._H = parseInt(args[3], 10);
							break;

						case "W":
							bkuid = args[0].substring(1);
							order = parseInt(args[2], 10);
							bindex = "B"+bkuid;
							if (!this.eachway[bindex]) { this.eachway[bindex] = {}; }
							this.eachway[bindex]["O"+order] = { bookmaker:bkuid, isChanged:true, text:args[1], order: order };
							tmp = args[1].match(/([1-9]+\/[1-9]+)[^0-9]*([0-9]).*([0-9])/);
							
							if (tmp && tmp.length >= 4 && tmp[3] != "1")
							{
								this.eachway[bindex].offered = tmp[1];
								this.eachway[bindex].places = tmp[2]+"-"+tmp[3];
							}
							else
							{
								this.eachway.splice(bindex, 1);
							}
							break;
						
						case "Z":
							this.priceConsumer.pollInterval = parseInt(args[0].substring(1), 10);
							this.outcomeConsumer.pollInterval = this.priceConsumer.pollInterval;
					}
					++this.outcomeCount;
				}
				if(!gotExtra) { this._showExtra = '0'; }

				oldOutcomes = null;
				this.sbHTML = this.getStatusbarHTML();
				this.sbHistRebuild = true;
				this.sbCurrRebuild = true;
			};




			/// Load new/changed price data into the price array for the relevant outcome
			_NS.prototype.loadPriceData = function(doc)
			{
				var i, j, uid, args, bki, price, data, localLastP, idx, curP, lastP, len;

				this._gotUpdate = true;
				this._prices = [];
				this._handicapMarket = false;
				len = doc.length;
				for(i = 0; i < len; i++) //>
				{
					if (doc[i] == null) break;

					data = doc[i];

					switch(data.substring(0, 1))
					{
						case 'B':

							uid = parseInt(data.substring(1), 10);
							if (this._outcomes["I"+uid] == null) break;
							args = data.split("|");
							bki = "B"+args[1];
							if(bki == "B9") break;
							if (!this.holder.bookieData[this.holder.bookieLnk[bki]]) { break; }


							price = {
								_uid : "I" + uid,
								_bookie : bki,
								_bookie_outcome : args[2],
								_bookie_SP : args[3],
								_bookie_price : args[4],
								_bookie_event : args[5],
								_bookie_meeting : args[6],
								_status : args[7],
								_handicap : args[9],
								_odds : [],
								_niceOdds : [],
								_dec : [],
								_pooldec : [],
								_suspended : false,
								_isBest : false
							};


							for(j = 0; j < 10; j += 2) //>
							{
								price._odds[j / 2] = args[10 + j];
								if (this.holder.params.sport == "Greyhounds")
									price._niceOdds[j / 2] = args[10 + j];
								else
									price._niceOdds[j / 2] = args[10 + j].replace(/\/1$/, "");	
								price._dec[j / 2] = parseFloat(args[11 + j], 10); 
								price._pooldec[j / 2] = args[11 + j];
							}
							if(price._status == 'H') { price._suspended = true; }
							localLastP = -1.0;
							try
							{
								if (typeof(this.holder.bookieLnk[price._bookie]) == "number")
								{
									idx = this.holder.bookieLnk[price._bookie];
									if (this._outcomes[price._uid]._prices[idx])
									{
										localLastP =  this._outcomes[price._uid]._prices[idx]._dec[0];
									}
								}
							}
							catch(e) {}
							try { this._outcomes[price._uid]._prices[this.holder.bookieLnk[price._bookie]] = price; }
							catch(e1) {}

							price._hue = "0";
							curP = price._dec[0]; lastP = price._dec[1];
							if (curP != null)
							{
								if (curP > 0.0)
								{
									if (lastP > 0.0)
									{
										if (curP > lastP) price._hue = "2";
										else if (curP == lastP) price._hue = "0";
										else price._hue = "1";
									}
								}
							}
							price._changed = (curP != localLastP);
							price._highlight = (localLastP != -1 && curP != localLastP);
							if(price._handicap != "")
								this._handicapMarket = true;
							break;

						case 'C':
							args = data.split("|");
							if(args[0].substring(1) == "9") break;
							this._suspendTimes["B"+args[0].substring(1)] = {_time : parseInt(args[1], 10) * 1000, _suspended : false};
							break;

						case 'Z':
							args = data.split("|");
							this.priceConsumer.pollInterval = parseInt(args[0].substring(1), 10);
							break;
					}
				}
			};

			_NS.prototype.checkSuspendThread = function()
			{
				var _this = this;
				
				if (this.checkSuspend())
				{
					this.genBestPrice();
					this.pleaseRepaint("check suspend thread");
				}				
				this.suspendTid = setTimeout(function () { _this.checkSuspendThread(); }, 1000);
			};

			_NS.prototype.checkSuspend = function()
			{
				var regen, i, j;
				
				this._checkSusDel = 0;
				regen = false;
				for(i in this._suspendTimes)
				{
					if(this._suspendTimes[i]._time == 0) { continue; }

					if(this.holder.dataObject.systemTime.getTime() > this._suspendTimes[i]._time && !this._suspendTimes[i]._suspended)
					{
						regen = true;
						this._suspendTimes[i]._suspended = true;
						for(j in this._outcomes)
						{
							try
							{
								if(this._outcomes[j]._prices[this.holder.bookieLnk[i]] != null)
									this._outcomes[j]._prices[this.holder.bookieLnk[i]]._suspended = true;
							}
							catch(e) { }
						}
					}
					else
					{
						if(this.holder.dataObject.systemTime.getTime() < this._suspendTimes[i]._time && this._suspendTimes[i]._suspended) // >
						{
							regen = true;
							this._suspendTimes[i]._suspended = false;
							for(j in this._outcomes)
							{
								try
								{
									if(this._outcomes[j]._prices[this.holder.bookieLnk[i]] != null)
										this._outcomes[j]._prices[this.holder.bookieLnk[i]]._suspended = (this._outcomes[j]._prices[this.holder.bookieLnk[i]]._status == "H");
								}
								catch(e1) { }
							}
						}
					}
				}
				return regen;
			};

			_NS.prototype.loadComplete = function()
			{
				if (!this._gotUpdate) return;
				this.checkSuspend();
				this.genBestPrice();
				this.genBookiePercents();
				this.pleaseRepaint("load complete");
			};

			_NS.prototype.genBookiePercents = function()
			{
				var b, o, outcome, bookie, price, best;
				
				this.columnPercents = [];
				for (b in this.holder.bookieData)
				{
					this.columnPercents[b] = 0.0;
				}
				this.columnPercents.Best = 0.0;

				for(o in this._outcomes)
				{
					outcome = this._outcomes[o];
					best=null;

					for (b in this.holder.bookieData)
					{
						bookie = this.holder.bookieData[b];
						try
						{
							price = outcome._prices[this.holder.bookieLnk[bookie._id]];
							if (!price) continue;
							if (price._suspended || price._dec[0] < 1.1) continue; //>
							this.columnPercents[b] += 100/price._dec[0];
							if (price._isBest && best == null)
								best = price;
						}
						catch (e)
						{
							this.columnPercents[b] += 0.0;
						}
					}
					if (best != null)
						this.columnPercents.Best += 100/best._dec[0];
				}
				for (b in this.columnPercents)
				{
					if (this.columnPercents[b] == 0.0)
						this.columnPercents[b] = "";
					else
						this.columnPercents[b] = Math.ceil(this.columnPercents[b])+"%";
				}

			};

			_NS.prototype.genBestPrice = function()
			{
			var outcome, price, bestPrice, i, j;

				this._gotUpdate = false;
				for(i in this._outcomes)
				{
					bestPrice = null;
					outcome = this._outcomes[i];

					outcome.numPrices = 0;
					for(j in outcome._prices)
					{
						if (this.holder.bookieData[j] == null) continue;
						price = outcome._prices[j];
						if(!this.holder.bookieData[j]._smartSort)
						{
							price._isBest = false;
							continue;
						}
						if(price._suspended) continue;
						++outcome.numPrices;
						if (outcome.isUnFav) continue;
						if(bestPrice == null)
						{
							bestPrice = price;
							continue;
						}
						if(price._dec[0] > bestPrice._dec[0])
						{
							bestPrice = price;
							continue;
						}
					}
					if(bestPrice != null)
					{
						for(j in outcome._prices)
						{
							price = outcome._prices[j];
							if (this.holder.bookieData[j] == null) continue;

							if(!this.holder.bookieData[j]._smartSort || price._suspended)
							{
								price._isBest = false;
							}
							else
							{
								if(price._dec[0] == bestPrice._dec[0])
								{
									price._isBest = true;
								}
							}
						}
					}
					this._outcomes[i]._bestPrice = bestPrice;
				}
			};

			_NS.prototype.pleaseRepaint = function(by)
			{
				var _this;
				
				this._repaintCount = 3;
				if (this.checkTid == null)
				{	
					_this = this;
					this.checkTid = setTimeout(function () { _this.checkStuff(); }, 10);
				}
			};

			_NS.prototype.checkStuff = function()
			{
				var _this;
				
				switch(this._repaintCount)
				{
					case 0 :
						this.checkTid = null;
						break;

					case 1:
						if (this._outcomes_tmp == null)
						{
							this._repaintCount = 300;
							break;
						}
						this._repaintCount = 0;
						this.doRepaint();
						this.checkTid = null;
						break;

					default:
						--this._repaintCount;
						_this = this;
						this.checkTid = setTimeout(function () { _this.checkStuff(); }, 10);
						break;
				}
			};

			_NS.prototype.changeHighlight = function(priceEl)
			{
				priceEl.setAttribute("lum", "90");
				this.highlightThread(priceEl);
			};

			_NS.prototype.highlightThread = function(priceEl)
			{
				var lum, _this;
				
				lum = parseInt(priceEl.getAttribute("lum"), 16);
				priceEl.setAttribute("lum", (lum+1).toString(16));

				if (lum >= 242) { priceEl.firstChild.style.backgroundColor = "transparent"; return; }
				priceEl.firstChild.style.backgroundColor = "rgb(242, 242, "+lum+")"; //"#ffff9e";
				_this = this;
				setTimeout(function() { _this.highlightThread(priceEl); }, 30);
			};

			_NS.prototype._setup_ = true;
		} // end of class prototype build
		
		// constructor
		this.holder = params.holder;
		this.holder.setupRender(this);

		this._uid = "0000000000" + params.uid;
		this._uidI = parseInt(params.uid, 10);
		this._uid = this._uid.substr(this._uid.length - 10, 10);
		this._outcomes = null;
		this._outcomes_tmp = null;
		this._gotUpdate = false;
		this._suspendTimes = [];
		this._title = {_show : '0', _text : ""};
		this._offtime = {_show : '0', _text : ""};
		this._tv = {_show : '0', _text : "", _W : 0, _H : 0, _URL : ""};
		this._spread = {_show : '0', _text : "", _W : 0, _H : 0, _URL : ""};
		this._betfair = {_show : '0', _text : "", _W : 0, _H : 0, _URL : ""};
		this._first = params.isFirst;
		this._showExtra = '0';
		this._height = -1;
		this._extra = [];
		this._handicapMarket = false;
		this.suspendTid = 0;
		this.checkTid = null;
		this.max_shown = 0; 
		this.show_span = null; 
		this.columnPercents = [];
		this.ready = false;
		this.started = false;
		this.ricegrainPrices = null;
		this.dataStore = [];
		this.eachway = [];
		var _this = this;

		this.priceConsumer = {   pollInterval:30, type:"Prices", prefix:"P", id:this._uid, onChange:function(n) {_this.loadPriceData(n);  }, getTitle:function() { return "Prices "+_this.getTitle(); }, boss:_this };
		this.outcomeConsumer = { pollInterval:30, type:"Market", prefix:"M", id:this._uid, onChange:function(n) {_this.loadOutcomeData(n);}, getTitle:function() { return "Markets "+_this.getTitle(); }, boss:_this };

		if(params.uid > 0) { this.holder.marketList["M" + this._uidI] = this; }
		this.getProperties(); // get geometry from subclass
		return true;	
	} // end of MarketClass



	
	, MarketGroup: function(params)
	{
		var _NS = RPOST.applet.MarketGroup;
		this.toolkit = RPOST.applet.toolkit;
		this.debug = RPOST.applet.toolkit.debug;
		
		if (!_NS.prototype._setup_) 
		{
			_NS.prototype.classname = "MarketGroup";
			
			_NS.prototype.startInstance = function()
			{
				if (typeof(this.startInstanceImpl) == "function") this.startInstanceImpl();
			}; 
			
			_NS.prototype.genFurniture = function()
			{
				if (typeof(this.genFurnitureImpl) == "function") this.genFurnitureImpl();
			};
		
			_NS.prototype.start = function ()
			{
				var i, args, _this, len, idx, btmp, id;

				this.dataObject = RPOST.applet.ATL;
				_this = this;

				if (this.params.bookies)
				{
					args = this.params.bookies.split("|");
					len = args.length;
					for(i = 0; i < len; i++)
					{
						if (args[i] == "Best")
						{
							this.showBestInColumn = true;
							continue;
						}
						try
						{
							if (typeof this.bookieLnk["B"+args[i]] == "number")
							{
								idx = this.bookieLnk["B"+args[i]];
								if (this.bookieData[idx])
									this.bookieData[this.bookieLnk["B"+args[i]]]._affid = 1;
							}
						}
						catch(e) { }
					}
					for(i in this.bookieData) ++this.numBookies; 			
				}
				
				args = this.affList.split("|");
				len = args.length;
				
				for(i = 0; i < len; i += 2)
				{
					try
					{
						if (typeof this.bookieLnk["B"+args[i]] == "number")
						{
							idx = this.bookieLnk["B"+args[i]];
							if (this.bookieData[idx])
								this.bookieData[this.bookieLnk["B"+args[i]]]._affid = args[i + 1];
						}
					}
					catch(e) {}
				}
				btmp = [];
				for(i in this.bookieData) { btmp[i] = this.bookieData[i]; }
				this.bookieData = btmp;

				if (this.params.marketIds == "multi") // lots of single prices from multi markets
				{
					this.isMulti = true;
				}
				else if (this.params.marketIds.indexOf("http") == -1)
				{
					args = this.params.marketIds.split("|");
					this.numMarkets = args.length;

					for(i = 0; i < this.numMarkets; i++)
					{
						id = parseInt(args[i], 10);
						if (!isNaN(id))
						{
							if(i == 0) { this.firstMarket = new RPOST.applet.MarketClass({holder:this, uid:id, isFirst:true}); }
							else { new RPOST.applet.MarketClass({holder:this, uid:id, isFirst:false}); }
						}
					}
				}
				else
				{
					this.metaURL = args;
				}
				this.addToATL(null);
				this.startInstance();	// applet specific setup
				if (this.params.prefix) setTimeout(function() {_this.notifyParentThread();}, 1);
				for (i in this.marketList)
					this.marketList[i].registerDataConsumers();
				this.pageRendered = true;
			};

			_NS.prototype.stop = function ()
			{
				var i;
				
				try
				{
					this.stopInstance();
					for (i in this.marketList) this.marketList[i].stop();
					this.dataObject.removeNotifyHandlers(this);
					this.toolkit.destroyObject(this.marketList);

					try
					{
						if (top.marketClassUnLoadNotifier)
							top.marketClassUnLoadNotifier();
					}
					catch (e) {}
					this.toolkit.stop();
				}
				catch (e) {}
			};

			_NS.prototype.addToATL = function()
			{
				this.dataObject.addPreNotifyHandler(this, function(mc) { mc.lockControls = true; });

				if (this.isMulti) this.dataObject.addRicegrainSearchHandler(this, function(ctx) { ctx.lookForRicegrainPrices(top.document); });

				this.dataObject.addPostNotifyHandler(this,
					function(ctx)
					{
						var i, t;
						
						for(i in ctx.marketList)
						{
							if (ctx.marketList[i]._gotUpdate === false)
							{
								ctx.lockControls = false;
								return;
							}
						}
						if(ctx.firstData)
						{
							if (ctx.getDispFormat() == "DECS")
							ctx.showDecs = true;
							if (ctx.targetList == null)	ctx.genFurniture("CURRENT");						
							else for (t in ctx.targetList) ctx.genFurniture("CURRENT", ctx.targetList[t].spanID);						
							ctx.lockControls = false;
							ctx.firstData = false;
						}
						else ctx.lockControls = false;

						for(i in ctx.marketList)
						{
							if (!ctx.marketList[i].started) ctx.marketList[i].start();
							ctx.marketList[i].loadComplete();
						}
					}
				);
			};

			_NS.prototype.notifyParentThread = function()
			{
				var _this = this, i;

				try
				{
					for (i in this.marketList)
					{
						if (!this.marketList[i].ready)
						{
							if (this.maxNotify-- > 0)
								setTimeout(function() {_this.notifyParentThread();}, 10);
							return;
						}
					}
					if (typeof (top.domReady) == "boolean" && top.domReady === false)
					{
						setTimeout(function() {_this.notifyParentThread();}, 10);
						return;
					}
					if (top[this.params.prefix+"marketClassLoadNotifier"])
						top[this.params.prefix+"marketClassLoadNotifier"](this.marketList);
				}
				catch (e) { }
			};
				
			_NS.prototype.lookForRicegrainPrices = function(doc)
			{
				var i, m, id, mk,  mks=[], lp, params;
				var kiddies, kid, k;
				
				for (i in this.marketList)
					this.marketList[i].ricegrainState = 0;

				for (i in RPOST.applet.ricegrainsToLookFor)
				{
					params = RPOST.applet.ricegrainsToLookFor[i];
					if (typeof(params) != "object") continue;
					lp = this.toolkit.getElement(params.divId);					

					params.priceboxID = "M"+params.priceboxID;
					params.outcomeID = "I"+params.outcomeID;
					params.bookieID = "B"+params.bookieID;					
					
					if (mks[params.priceboxID] == null) mks[params.priceboxID] = {shown:[]};
					mk = mks[params.priceboxID];

					kiddies = lp.childNodes;
					for (k in kiddies)
					{
						kid = kiddies[k];
						if (!kid.className) continue;
						if (kid.className.indexOf("live_outcome") != -1) params.nameEl = kid; 
						else if (kid.className.indexOf("live_price") != -1) params.outcomeEl = kid;
						else if (kid.className.indexOf("live_betnow") != -1) params.butEl = kid;						
					}
					mk.shown.push(params);
				}
				for (i in this.marketList)
				{
					 this.marketList[i].stop();
					 delete(this.marketList[i]);
				}
				this.marketList = [];
				this.firstData = true;
				for (m in mks)
				{
					id = parseInt(m.substr(1), 10);
					if (!isNaN(id))
					{
						mk = new RPOST.applet.MarketClass({holder:this, uid:id, isFirst:false});
						mk.ricegrainState = 1;
						mk.sport = mks[m].shown[0].sport;
						mk.pageRef = mks[m].shown[0].pageRef;
						mk.sectionId= mks[m].shown[0].sectionId;
						mk.locationId= mks[m].shown[0].locationId;
						mk.productId= mks[m].shown[0].productId;
						mk.ricegrainPrices = mks[m].shown;
						mk.registerDataConsumers();
					}
				}
			};

// This will be used soon.			
			_NS.prototype.fireScore = function(productId, sectionId, locationId, bookieId, marketId, outcomeId, desc)
			{
//				var data = "<?xml version='1.0' encoding='UTF-8' ?><SL><List __isArrayHolder='Score'>"+
//						"<SD t='4' sid='"+sectionId+"' pid='"+productId+"' lid='"+locationId+"' i1='"+bookieId+"' i2='"+marketId+"' i3='"+outcomeId+"'>"+desc+"</SD></List></SL>"
//				$.ajax(
//				{
//					  type: "POST"
//					, url: this.params.scorecardURL
//					, contentType: "text/xml"
//					, dataType: "text"
//					, async: true
//					, data: data
//				});			
			};

			_NS.prototype.Bet = function(marketIdx, outcomeIdx, bookieIdx)
			{
				var sport, mkt, sectionId, bookie, URL, res, i, pageRef, locationId, productId;
				
				mkt = this.marketList["M" + marketIdx];				
				bookie = this.bookieData[bookieIdx];
				sport = this.params.sport;
				pageRef = this.params.pageRef;
				sectionId = this.params.sectionId;
				locationId = this.params.locationId;
				productId = this.params.productId;

				if (mkt.ricegrainPrices != null)
				{
					for (i in mkt.ricegrainPrices)
					{
						if (mkt.ricegrainPrices[i].outcomeID == outcomeIdx)
						{
							sport = mkt.ricegrainPrices[i].sport;
							pageRef = mkt.ricegrainPrices[i].pageRef;
							sectionId = mkt.ricegrainPrices[i].sectionId;
							locationId = mkt.ricegrainPrices[i].locationId;
							productId = mkt.ricegrainPrices[i].productId;
							break;
						}
					}
				}

				this.fireScore(productId, sectionId, locationId, bookie._CRid, marketIdx, outcomeIdx.substring(1), pageRef); 

				URL = mkt.getBetslipURL(outcomeIdx, bookieIdx);

				res = window.open(URL, bookie._betslip_name, "width=" + bookie._W + ",height=" + bookie._H + ",resizable"+bookie.bsScroll);
				res.focus();				
				if (navigator.userAgent.indexOf("JONAH_TEST") > 0)
				{
					var bits = ["", "", "", ""], n=0;
					URL = URL.replace(/&/g, "+");
					while (URL.length > 50)
					{
						bits[n++] = URL.substring(0, 50);
						URL = URL.substring(50);
					}
					bits[n] = URL;
					URL = parseInt(marketIdx, 10) + "&" +
					this.bookieData[bookieIdx]._CRid + "&" + // use the integer rather than the string needed for pools support
					outcomeIdx.substring(1) + "&" +
					mkt.getPrice(outcomeIdx, bookieIdx) + "&" +
					sport + "&" +
					3141 + "&" +	// screen W
					2718 + "&" +	// screen H
					pageRef + "&" +
					this.bookieData[bookieIdx]._reportType + "&" +
					bits[0] + "&" +
					bits[1] + "&" +
					bits[2] + "&" +
					"0" + "&" +
					bits[3];
				}
				else
				{
					URL = parseInt(marketIdx, 10) + "&" +
					this.bookieData[bookieIdx]._CRid + "&" + // use the integer rather than the string needed for pools support
					outcomeIdx.substring(1) + "&" +
					mkt.getPrice(outcomeIdx, bookieIdx) + "&" +
					sport + "&" +
					0 + "&" +	// screen W
					0 + "&" +	// screen H
					pageRef + "&" +
					this.bookieData[bookieIdx]._reportType + "&" +
					"&" +
					"&" +
					"&" +
					this.getUserID()+"&" +
					this.toolkit.getCookie("PermRpLogin")
				}				

				URL = URL.replace(/ /g, "%20");
				this.dataObject.pushMessage("/applet", "9,"+URL.length+","+URL);
			};

			_NS.prototype.getDispFormat = function()
			{
				var ret;

				if (RPOST.userPrefs != null && typeof (RPOST.userPrefs) == "object" && RPOST.userPrefs.getFormat) ret = RPOST.userPrefs.getFormat();
				else if (this.params.disp == "frac" ) ret = "ODDS";
				else if (this.params.disp == "decs" ) ret = "DECS";
				else ret = "FRAC";
				return ret;
			};
			
			_NS.prototype.setDispFormat = function(s) 	{  };
			_NS.prototype.getVersion = function() 		{ return "HTMLpb: 9.4"; };

			_NS.prototype.getUserID = function()
			{
				if (RPOST.userPrefs != null && typeof (RPOST.userPrefs) == "object") return RPOST.userPrefs.getUserIDs().reg_uid;
				else return this.toolkit.getCookie("RP_UID");
			};

			_NS.prototype.getUserMD5 = function()
			{
				if (RPOST.userPrefs != null && typeof (RPOST.userPrefs) == "object") return RPOST.userPrefs.getUserIDs().reg_md5;
				else return this.toolkit.getCookie("RP_MD5_COOKIE");
			};

			_NS.prototype.getUserBookies = function()
			{
				var list, ret, i;
				try
				{
					list = RPOST.userPrefs.getUserIDs().bookmakerPreferences.split("|");
				}
				catch (e) { list = "2|3|6|7|8|10|11|12|14|16|17|15".split("|"); }
				list = "2|3|6|7|8|10|11|12|14|16|17|15".split("|");
				ret = [];
				for (i in list)
					ret[this.bookieLnk["B"+list[i]]] = "1";

				return ret;
			};
			_NS.prototype._setup_ = true;
		} // end of class prototype build
		
		
		this.params = params; //InstanceName, marketIds, pageRef,  bookies, format, mustLogin, prefix, sport, renderType				
		this.bust = true;
		this.setupRender=function() {  };
		switch(params.renderType)
		{
			case "renderAsData": this.setupRender = RPOST.applet.setupRenderAsData; break;
			case "renderAsRicegrains": this.setupRender = RPOST.applet.setupRenderAsRicegrains; break;
			case "renderAsBox": this.setupRender = RPOST.applet.setupRenderAsBox; break;
			default:
				return false;
		}		
		this.bust = false;
		this.showBestInColumn = false;
		this.bookieData = [];			
		this.marketList = [];
		this.affList = null;
		this.dataObject="";
		this.isMulti = false;
		this.numMarkets=0;
		this.numBookies = 0;
		this.lockControls = false;
		this.debugStruct=null;
		this.metaURL = null;
		this.targetList = null;
		this.pageRendered = false;
		this.showDecs = false;
		this.firstMarket=null;
		this.frameShown="C_";
		this.mages = [];
		this.maxNotify = RPOST.maxSyncRetries;

		this.firstData=true;
		this.RPdomain="";

		this.DBclikerTid=null;
		this.bookieChooser=null;
		
		var affSets = 
		{	  DEFAULT:			"2|a_22452b_3423|3|310|4|154|6|252|7|30|8|10001|10|2311|11|4070|12|RAP10|14|262|0|0|16|0|17|3631|15|101990"
			, RACINGPOST :	"2|2604|3|310|4|154|6|252|7|30|8|10001|10|2311|11|4070|12|RAP10|14|262|0|0|16|0|17|3631|15|101990"
			, TBSBETA:		"2|a_11823b_3423|3|310|4|154|6|252|7|30|8|10001|10|2311|11|4070|12|RAP10|14|262|0|0|16|0|17|3631|15|101990"
			, MYRACINGPOST:	"2|2604|3|310|4|154|6|22640|7|30|8|10001|10|2311|11|4070|12|RAP10|14|262|0|0|16|0|17|3631|15|101990"
			, C4:				"2|2604|3|310|4|154|6|252|7|30|8|10001|10|2311|11|4070|12|RAP10|14|262|0|0|16|0|17|3631|15|101990"
		};

		if (params.affSet) this.affList = affSets[params.affSet];
		if (this.affList === null) this.affList = affSets.DEFAULT;
					
		if (params.style)
			this.toolkit.includeStyle(RPOST.appletRoot+"/Styles/"+params.style);
	
		// bookie ID -> array position lookup table
		this.bookieLnk = [];
		this.bookieLnk.B11 = 0 ;   //ladbrokes
		this.bookieLnk.B16 = 1 ; // william hill
		this.bookieLnk.B8 = 2 ;  // paddy power
		this.bookieLnk.B12 = 3 ;  // bet365
		this.bookieLnk.B6 = 4 ;   // bluesq
		this.bookieLnk.B2 = 5 ;  // sporting bet
		this.bookieLnk.B7 = 6 ;   // skybet
		this.bookieLnk.B17 = 7 ; // boyles
		this.bookieLnk.B10 = 8 ;  // vcbet
		this.bookieLnk.B14 = 9 ; // betfred
//		this.bookieLnk.B15 = 10 ; // stan james

		this.bookieData[3] = {
			_id : "B12",
			_CRid : "12",
			_name : "Bet365",
			_sendMD5 : true,
			_showTV : true,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "B",
			_TV_img : "tv_icon.gif",
			_betslip_name: "_blank",
			_affid : -1, _W : 590, _H : 660, bsScroll:"",
			_img1 : "B12_rgb", _img2 : "B12_bw", bkchooserImg:"B12", bigImage:"bet365_pb_header.gif",
			_hue1 : "00673E", _hue2 : "B2D1C5",
			_url : "http://www.bet365.com/instantbet/default.asp?participantid=%u&affiliatecode=%a$%i&odds=%p&instantbet=1"
		};


		this.bookieData[0] = {
			_id : "B11",
			_CRid : "11",
			_name : "Ladbrokes",
			_sendMD5 : true,
			_showTV : true,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "B",
			_TV_img : "tv_icon.gif",
			_betslip_name: "_blank",
			_affid : -1, _W : 410, _H : 645, bsScroll:"",
			_img1 : "B11_rgb", _img2 : "B11_bw", bkchooserImg:"B11", bigImage:"ladbrokes_pb_header.gif",
			_hue1 : "FE000C", _hue2 : "FFB2B6",
			_url : "http://www.ladbrokes.com/lbr_sports?action=go_sgl_external&popup=1&AFF_ID=%a&ev_oc_id=%u&lp_num=%n&lp_den=%d&RP_CustID=%i"
		};

		this.bookieData[2] = {
			_id : "B8",
			_CRid : "8",
			_name : "Paddy Power",
			_sendMD5 : true,
			_showTV : true,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "N",
			_TV_img : "",
			_betslip_name: "_blank",
			_affid : -1, _W : 375, _H : 350, bsScroll:"",
			_img1 : "B8_rgb", _img2 : "B8_bw", bkchooserImg:"B8", bigImage:"paddy_power_pb_header.gif",
			_hue1 : "009951", _hue2 : "B2E0CA",
			_url : "https://www.paddypower.com/bet?action=go_gmulti&ev_oc_id=%u&AFF_ID=%a&lp_num=%n&lp_den=%d&RP_CustID=%i"
		};

		this.bookieData[6] = {
			_id : "B7",
			_CRid : "7",
			_name : "Skybet",
			_sendMD5 : true,
			_showTV : true,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "N",
			_TV_img : "",
			_betslip_name: "_blank",
			_affid : -1, _W : 800, _H : 500, bsScroll:"",
			_img1 : "B7_rgb", _img2 : "B7_bw", bkchooserImg:"B7", bigImage:"skybet_pb_header.gif",
			_hue1 : "091858", _hue2 : "B5B9CD",
			_url : "https://www.skybet.com/secure/rbs?action=go_gmulti&ev_oc_id=%u&lp_num=%n&lp_den=%d&AFF_ID=%a&RP_CustID=%i"
		};
		this.bookieData[9] = {
			_id : "B14",
			_CRid : "14",
			_name : "Bet Fred",
			_sendMD5 : false,
			_showTV : false,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "N",
			_TV_img : "",
			_betslip_name: "_rp_betfred",
			_affid : -1, _W : 594, _H : 550, bsScroll:",scrollbars",
			_img1 : "B14_rgb", _img2 : "B14_bw", bkchooserImg:"B14", bigImage:"betfred_pb_header.gif",
			_hue1 : "225493", _hue2 : "BCC6E2",
			_url : "http://www.betfred.com/betslip/betsliplanding.asp?selid=%u&price=%p&betsrcid=%a"
		};


		this.bookieData[4] = {
			_id : "B6",
			_CRid : "6",
			_name : "Blue Square",
			_sendMD5 : true,
			_showTV : false,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "B",
			_TV_img : "tv_icon.gif",
			_betslip_name: "_blank",
			_affid : -1, _W : 450, _H : 650, bsScroll:"",
			_img1 : "B6_rgb", _img2 : "B6_bw", bkchooserImg:"B6", bigImage:"bluesq_pb_header.gif",
			_hue1 : "21429F", _hue2 : "BCC6E2",
			_url : "https://www.bluesq.com/secure/bet?action=GoBetAdd&leg=|%t|%n|%d|||%u&remote=Y&AFF_ID=%a&RP_CustID=%i"
		};

		this.bookieData[5] = {
			_id : "B2",
			_CRid : "2",
			_name : "Sporting Bet",
			_sendMD5 : false,
			_showTV : false,
			_decsOnly : false,
			_smartSort : false,
			_priceStyle : "0",
			_reportType: "N",
			_TV_img : "",
			_sportIDs : {Horses:171, Greyhounds:32 },
			_betslip_name: "_rp_sporting",
			_affid : -1, _W : 572, _H : 523, bsScroll:",scrollbars",
			_img1 : "B2_rgb", _img2 : "B2_bw", bkchooserImg:"B2", bigImage:"sporting_bet_pb_header.gif",
			_hue1 : "2899ff", _hue2 : "99ddff",
			_url : "http://www.sportingbet.com/t/mini/betSlip.aspx?affiliate=ia_com&pname=%a&sp=%s&evid=%e&mktid=%m&selid=%u&price=%p"
		};

		this.bookieData[8] = {
			_id : "B10",
			_CRid : "10",
			_name : "VCBet",
			_sendMD5 : true,
			_showTV : false,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "N",
			_TV_img : "tv_icon_bar.gif",
			_betslip_name: "_blank",
			_affid : -1, _W : 1000, _H : 850, bsScroll:",scrollbars",
			_img1 : "B10_rgb", _img2 : "B10_bw", bkchooserImg:"B10", bigImage:"vc_bet_pb_header.gif",
			_hue1 : "000000", _hue2 : "BAE6F5",
//			_url : "http://classic.vcbet.com/remotebetslip/betslip_add.jsp?MeetingId=%m&EventId=%e&OppId=%u&PriceId=%x&OID=%a&RP_CustID=%i"
			_url: "http://www.victorchandler.com/vcbet/en-gb/coupon/remote/%e/%u/%x?OID=%a"
		};

		this.bookieData[1] = {
			_id : "B16",
			_CRid : "16",
			_name : "William Hill",
			_sendMD5 : false,
			_showTV : false,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "N",
			_TV_img : "",
			_betslip_name: "_blank",
			_affid : -1, _W : 1000, _H : 850, bsScroll:",scrollbars",
			_img1 : "B16_rgb", _img2 : "B16_bw",bkchooserImg:"B16", bigImage:"none",
			_hue1 : "000000", _hue2 : "909090",
			_url : "http://sports.williamhill.com/bet/EN/betting/m/%x"
		};

		this.bookieData[7] = {
			_id : "B17",
			_CRid : "17",
			_name : "BoyleSports",
			_sendMD5 : false,
			_showTV : false,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "N",
			_TV_img : "",
			_betslip_name: "_blank",
			_affid : -1, _W : 700, _H : 600, bsScroll:",scrollbars",
			_img1 : "B17_rgb", _img2 : "B17_bw", bkchooserImg:"B17", bigImage:"none",
			_hue1 : "000000", _hue2 : "909090",
//			_url: "http://warp.boylesports.com/Areas/ExtBetslip/Template_1_UK/index.html#oc_idfomarket=%m&oc_idfoselection=%u&idfiacampaign=%a"   
//			_url: "http://www.boylesports.com/Areas/ExtBetslip/Template_1_UK/index.html#oc_idfomarket=%m&oc_idfoselection=%u&idfiacampaign=%a" (priceup=%n&pricedown=%d)
			_url : "http://classic.boylesports.com/betslip/betsliplanding.asp?selid=%u&price=%p&betsrcid=%a&idfiadvert=21&fimsoec=1&idfiacampaign=%a" 
		};		

/*		
		this.bookieData[10] = {
			_id : "B15",
			_CRid : "15",
			_name : "Stan James",
			_sendMD5 : true,
			_showTV : true,
			_decsOnly : false,
			_smartSort : true,
			_priceStyle : "0",
			_reportType: "N",
			_TV_img : "",
			_betslip_name: "_blank",
			_affid : -1, _W : 800, _H : 500, bsScroll:"",
			_img1 : "B15_rgb", _img2 : "B15_bw", bkchooserImg:"B15", bigImage:"skybet_pb_header.gif",
			_hue1 : "091858", _hue2 : "B5B9CD",
			_url : "http://www.stanjames.com/betslip/BetslipLanding.asp?fimsid=%a&selid=%u&price=%p"
		};
*/
		return true;
	} // end of MarketGroup class
		
	
// Data only pricebox render
	, setupRenderAsData: function(mkt)
	{	
		mkt.getPropertiesImpl = function()
		{
			this.outcomeContainer = null;
		};

		mkt.doSort = function()
		{
			var ret;

			if (this._outcomes_tmp == null)
			{
				return;
			}

			this._outcomes_tmp.sort(function(Pa, Pb)
			{
				if (isNaN(Pa._orderby))
				{
					if (!isNaN(Pb._orderby)) return 1;
				}
				else
				{
					if (isNaN(Pb._orderby)) return -1;
					return Pa._orderby - Pb._orderby;
				}
				if (Pa._bestPrice == null)
				{
					if (Pb._bestPrice == null) ret = 0; else ret = 1;
				}
				else if (Pb._bestPrice == null) ret = -1;
				else if (Pb._bestPrice._dec[0] == 0) ret = -1;
				else if (Pa._bestPrice._dec[0] == 0) ret = 1;
				else
				{
					ret = (Pa._bestPrice._dec[0] - Pb._bestPrice._dec[0]);
				}
				if (ret == 0)
				{
					if (Pa.numPrices > Pb.numPrices) return -1;
					if (Pa.numPrices < Pb.numPrices) return 1;
					if (Pa._name > Pb._name) return 1;
					if (Pa._name == Pb._name) return 0;
					return -1;
				}
				return ret;
			});
		};

		mkt.doRepaint = function()
		{
			this.doSort();
			if (this.outcomeContainer === null) // create a new structure and fill in data
			{
				this.outcomeContainer = new OutcomeContainerClass(this); // notify func will be called afterwards; when it's registered
				this.ready = true;
			}
			else if (this.outcomeContainer.update() && typeof(this.priceChangeNotifyFunc) == 'function')
			{
				this.priceChangeNotifyFunc(this.outcomeContainer.marketIdx, null);
			}
		};

		mkt.registerPriceChangeNotify = function(func)
		{
			this.priceChangeNotifyFunc = func;
			if (typeof(func) == 'function')
			{
				this.priceChangeNotifyFunc = func;
				try {
					this.priceChangeNotifyFunc(this.outcomeContainer.marketIdx, this.outcomeContainer);
				} catch (e){ this.debug(e); }
			}
		};

		function OutcomeContainerClass(market)
		{
			OutcomeContainerClass.prototype.classname = "OutcomeContainerClass";
			this.outcomeDataList = [];
			this.eachwayTerms = [];
			this.marketRef= market;
			this.marketIdx = "M"+market._uid;
			var o;

			for (o in market._outcomes_tmp)
				this.outcomeDataList[market._outcomes_tmp[o]._uid] = new OutcomeDataClass(this, market._uidI, market._outcomes_tmp[o]);
							for (o in market.eachway) this.eachwayTerms[o] = market.eachway[o];

			OutcomeContainerClass.prototype.getList = function()
			{
				return this.outcomeDataList;
			};

			OutcomeContainerClass.prototype.launchBetslip = function(outcomeIdx, priceIdx)
			{
				this.outcomeDataList[outcomeIdx].launchBetslip(priceIdx);
			};

			OutcomeContainerClass.prototype.getSPPercents = function()
			{
				return this.marketRef.columnPercents;
			};

			OutcomeContainerClass.prototype.update = function()
			{
				var o, changed = false;
				for (o in this.marketRef._outcomes_tmp) 
					if (this.outcomeDataList[this.marketRef._outcomes_tmp[o]._uid].update(this.marketRef._outcomes_tmp[o]))
						changed = true;
				for (o in market.eachway) this.eachwayTerms[o] = market.eachway[o];						
				return changed;
			};

			function OutcomeDataClass(container, mktID, out)
			{
				OutcomeDataClass.prototype.classname = "OutcomeDataClass";
				var p;
				this.outcomeUid = new Number(out._CRid);
				this.activePriceCount = out.numPrices;
				this.isUnnamedFavourite = out.isUnFav;
				this.prices = [];
				this.isChanged = true;
				this.containerRef = container;

				for (p in out._prices)
					this.prices[p] = new PriceDataClass(this, mktID, out._prices[p]);

				OutcomeDataClass.prototype.update = function(out)
				{
					this.isChanged = false;
					for (p in this.prices)
					{
						if (this.prices[p].update(out._prices[p]))
							this.isChanged = true;
					}
					return this.isChanged;
				};

				OutcomeDataClass.prototype.launchBetslip = function(priceIdx)
				{
					this.prices[priceIdx].launchBetslip();
				};

				function PriceDataClass(outcome, mktID, price)
				{
					PriceDataClass.prototype.classname = "PriceDataClass";
					this.bookieID = price._bookie;
					this.handicap = price._handicap;
					this.isChanged = price._changed;
					this.canHighlight = price._highlight;
					this.isBest = price._isBest;
					this.isSuspended = price._suspended;
					this.fractionOdds = price._niceOdds;
					this.decimalOdds = price._dec;
					this.outcomeRef = outcome;
					this.mktID = mktID;

					PriceDataClass.prototype.launchBetslip = function()
					{
						var mg = this.outcomeRef.containerRef.marketRef.holder;
						mg.Bet(this.mktID, "I"+this.outcomeRef.outcomeUid, mg.bookieLnk[this.bookieID]);
					};

					PriceDataClass.prototype.update = function(newPrice)
					{
					    this.isBest = newPrice._isBest;// update isBest required for changed and not changed prices
						if (!newPrice._changed && this.isSuspended == newPrice._suspended && this.handicap == newPrice._handicap)
							this.isChanged = false;
						else
						{
							this.handicap = newPrice._handicap;
							this.isChanged = true;
							this.canHighlight = newPrice._highlight;
							this.isSuspended = newPrice._suspended;
							this.fractionOdds = newPrice._niceOdds;
							this.decimalOdds = newPrice._dec;
						}
						return this.isChanged;
					};
				}
			}
		}
	} // end of setupRenderAsData	 







// Ricegrain (Bet Now buttons on page) market render 
	, setupRenderAsRicegrains: function(mkt)
	{
		var _NS = RPOST.applet.MarketClass;
		
		mkt.getPropertiesImpl = function()
		{
			this.missingRetry=0;
			this.outcomeRowsCount=0;
			this.expectedOutcomeRowsCount=0;
			this.lastSortValue="Best";
			this.lastSortType="SMART";
			this.lastSortDir="UP";
			this.historyShown = false;
			this.initialSort=true;
			this.outcomeRowBorder = -1;
			this.sort_prompt_el = null;
			this.histBookie=null;
		};

		mkt.doRepaint = function()
		{
			var missingIDs, _this, i, r, grain, outcome, bk, bookie, price, idx, bookiePrefs, txt, title, onclick, bestPrices, and, comma, list;
			
			bookiePrefs = this.holder.getUserBookies();
			missingIDs = false;
			if (!this.holder.pageRendered)
			{
				_this = this;
				if (_this.missingRetry > 10) return;
				setTimeout(function() { _this.pleaseRepaint("page not complete "+(++_this.missingRetry)); }, 0);
				return;
			}

			this.ready = true;

			if (this.ricegrainPrices !== null)
			{
				for (r in this.ricegrainPrices)
				{
					grain = this.ricegrainPrices[r];
					outcome = this._outcomes[grain.outcomeID];
					if (outcome == null) { grain.outcomeEl.innerHTML = "no price"; continue; }
					if (outcome._prices.length == 0) continue; // no prices yet? ATL will nudge us when they turn up
					if (grain.bookieID == "BBest")
					{
						bestPrices = { offeringBookies:[], isBest:[], bestPrice:-1, outcome:outcome  };
						for (bk in this.holder.bookieData)
						{
							bookie = this.holder.bookieData[bk];
							price = outcome._prices[bk];
							if (price == null || ""+price == "undefined") continue;
							if ((price._isBest || bookiePrefs[bk] == "1") && !price._suspended )
							{
								idx = bestPrices.offeringBookies.push(bookie);
								if (price._isBest)
								{
									bestPrices.bestPrice = price;
									bestPrices.isBest[idx-1] = true;
								}
								else bestPrices.isBest[idx-1] = false;
							}
						}
						price = bestPrices.bestPrice;
						txt = ""; and=""; list = "["; comma="";
						for (i in bestPrices.offeringBookies)
						{
							if (!bestPrices.bestPrice == -1) continue;
							list += comma+this.holder.bookieLnk[bestPrices.offeringBookies[i]._id];
							comma=",";
							if (!bestPrices.isBest[i]) continue;
							txt += and+" "+bestPrices.offeringBookies[i]._name;
							and = ",  ";
						}
						list += "]";
						title = "Offered by " +txt+" - Click to bet";
						onclick = this.holder.params.instanceName+".bkChooser(this, '"+this._uidI+"','"+outcome._uid+"',"+list+")";
						this.getClickablePrice(grain.outcomeEl, grain.butEl, outcome, price, bookie, title, onclick, true);
					}
					else
					{
						bookie = this.holder.bookieData[this.holder.bookieLnk[grain.bookieID]];
						price = outcome._prices[this.holder.bookieLnk[grain.bookieID]];
						if (price == null || ""+price == "undefined") continue;

						onclick = this.holder.params.instanceName+".Bet('"+this._uidI+"','"+outcome._uid+"','"+this.holder.bookieLnk[grain.bookieID]+"')";
						title = price._odds[0]+" with "+bookie._name+"; Click to bet";
						this.getClickablePrice(grain.outcomeEl, grain.butEl, outcome, price, bookie, title, onclick, (bookie._url != null));
					}
					if (price._highlight)
						this.changeHighlight(grain.outcomeEl);
				}
				return;
			}
		};



		mkt.getClickablePrice = function(priceEl, butEl, outcome, price, bookie, title, action, clickable)
		{
		var HTML=[], butHTML=[];

			if (price == -1 || price._suspended)
			{
				if (typeof(butEl) != "object")
					HTML.push("<div class='odd' title='Price Suspended' style='vertical-align:middle;'>--");
				butHTML.push("<b style='color:#666666;'>No Betting</b>");
			}
			else
			{
				
				if (clickable)
				{
					HTML.push("<div class='odds up "+(price._isBest? "best":"bad")+"'");
					HTML.push(" onmousedown=\"$(this).addClass('down')\" onmouseup=\"$(this).removeClass('down')\" ");
					HTML.push(" title=\""+title+"\" onclick=\""+action+"\"");

					HTML.push("' >");
					butHTML.push("<div class='betnow up' onmousedown=\"$(this).addClass('betnow down')\" onmouseup=\"$(this).removeClass('down')\"'");
					butHTML.push(" title='"+title+"' onclick=\""+action+"\"</div>");
				}
				else
				{
					HTML.push("<div class='odds'>");
				}
				if ((this.holder.showDecs && price._dec[0] > 0.0) || bookie._decsOnly)
				{
					HTML.push("<span>"+price._dec[0]+"</span>");
				}
				else
				{
					try { HTML.push(price._niceOdds[0]); } catch (e) {}
				}
				if (price._handicap != "")
				{
					HTML.push("<sup style='color:#000000'>"+price._handicap+"</sup>");
				}
			}
			HTML.push("</div>");
			priceEl.innerHTML = HTML.join('');

			this.cachedInnerHtml(priceEl, "p"+outcome._CRid+" "+bookie._CRid, HTML.join(''));
			this.cachedInnerHtml(butEl, "b"+outcome._CRid+" "+bookie._CRid, butHTML.join(''));
		};



		mkt.holder._cck = false;
		mkt.holder.winClick = function(e)
		{
			if (!this._cck) this.popdownAndBet();
			this._cck = false;
			return false;
		};

		mkt.holder.chooClick = function(e)
		{
			this._cck = true;
			return false;
		};


		mkt.holder.bkChooser = function(s, marketID, outcomeID, bookieList)
		{
			var idx, d, chooser, market, outcome, i, oa, _this, e1, e2, price, txt, bestList, restList, bestAmt, dim, coords, Xpos, Ypos, Y;
			
			chooser = RPOST.applet.bookieChooser;
			if (chooser == null) return;
			market = this.marketList["M"+marketID];
			outcome = market._outcomes[outcomeID];
			
			this.fireScore(market.productId, market.sectionId, market.locationId, "", marketID, outcomeID.substring(1), "Bet Now");
			
			_this = this;
			this.e1 = function(e) {_this.winClick(e); };
			e1 = this.e1;
			this.e2 = function(e) {_this.chooClick(e); };
			e2 = this.e2;
		
			setTimeout(function() {
				if (document.addEventListener)
				{
					top.addEventListener("mousedown", e1, false);
					chooser.addEventListener("mousedown", e2, false);
				}
				else if (top.attachEvent)
				{
					top.document.attachEvent("onmousedown", e1);
					chooser.attachEvent("onmousedown", e2);
				}
			}, 100);

			price = outcome._prices[bookieList[0]];
			txt = ""; Y = 0;

			txt +=   "<span class='header'>" +
				       "<span class='title'>BEST ODDS</span>" +
				       "<span class='name'>"+outcome._name.toUpperCase()+"</span>" +
				       "<span class='close' title='Click to close' onclick=\""+this.params.instanceName+".popdownAndBet()\" ></span>" +
				       "<span class='colhead'><span class='ch bk'>BOOKIE</span><span class='ch tms'>E.W. TERMS</span><span class='ch pce'>PRICE</span></span>";
			Y = 68;

			bestList = []; restList = []; bestAmt = 0;
			for (i in bookieList)
			{
				idx = bookieList[i];
				price = outcome._prices[idx];
				if (price._isBest) { bestAmt = price._dec[0]; bestList.push({b: this.bookieData[idx], p:price, i:idx}); }
				else restList.push({b: this.bookieData[idx], p:outcome._prices[idx], i:idx});
			}
			for (i in restList)
			{
				d = restList[i];
				if (d.p._dec[0] == bestAmt)
				{
					bestList.push(d);
					delete(restList[i]);
				}
			}
			restList.sort(function(a, b) { if (a.p._dec[0] > b.p._dec[0]) return -1; if (a.p._dec[0] == b.p._dec[0]) return 0; return 1; });

			for (i in bestList)
			{
				d = bestList[i];
				txt += "<span class='row' style='top:"+Y+"px;' title='Click to bet...'";
				txt += "onMouseover=\"$(this).addClass('in')\" onMouseOut=\"$(this).removeClass('in')\"";
				txt += "onclick=\"  "+this.params.instanceName+".popdownAndBet('"+marketID+"','"+outcomeID+"','"+d.i+"');\">";
				txt += "<span class='bkimg "+d.b.bkchooserImg+"'></span>";
				if (market.eachway[d.b._id]) 
				{
					try {
					oa = market.eachway[d.b._id].offered.split("/");
					if (oa.length > 1)
						txt += "<span class='offered'><span class='num'>"+oa[0]+"</span>/<span class='den'>"+oa[1]+"</span></span><span class='terms'>"+market.eachway[d.b._id].places+"</span>";
					} catch (e1) {}
				}

				txt += "<span class='price'>";
				if (this.showDecs && d.p._dec[0] > 0.0) txt += d.p._dec[0];
				else txt += d.p._niceOdds[0];
				txt += "</span>";
				txt += "<span class='betnow' onmousedown=\"$(this).addClass('down')\" onmouseup=\"$(this).removeClass('down')\"'></span>";
				txt += "</span>";
				Y += 31;
			}
			txt += "<span class='sep' style=' top:"+(Y-1)+"px; '></span>";

			for (i in restList)
			{
				d = restList[i];
				txt += "<span class='row' style='top:"+Y+"px;' title='Click to bet...'";
				txt += "onMouseover=\"$(this).addClass('in')\" onMouseOut=\"$(this).removeClass('in')\"";
				txt += "onclick=\"  "+this.params.instanceName+".popdownAndBet('"+marketID+"','"+outcomeID+"','"+d.i+"');\">";
				txt += "<span class='bkimg "+d.b.bkchooserImg+"'></span>";
				if (market.eachway[d.b._id]) 
				{
					try {
					oa = market.eachway[d.b._id].offered.split("/");
					if (oa.length > 1)
						txt += "<span class='offered'><span class='num'>"+oa[0]+"</span>/<span class='den'>"+oa[1]+"</span></span><span class='terms'>"+market.eachway[d.b._id].places+"</span>";
					} catch (e2) {}
				}				
				txt += "<span class='price'>";
				if (this.showDecs && d.p._dec[0] > 0.0) txt += d.p._dec[0];
				else txt += d.p._niceOdds[0];
				txt += "</span>";
				txt += "<span class='betnow' onmousedown=\"$(this).addClass('down')\" onmouseup=\"$(this).removeClass('down')\"'></span>";
				txt += "</span>";		
				Y += 31;
			}
			
			Y -= 1;
			txt = "<span class='panel' style=' height:"+Y+"px; '>"+txt+"</span>";
			dim = this.toolkit.getWindowSize(top);
			coords = this.toolkit.findPos(s);
			Xpos = coords.X> (dim.W-240)? coords.X-230:coords.X+30;
			if (Xpos < 0) Xpos = 0;
			Ypos = coords.Y > (dim.H-Y)? coords.Y-Y:coords.Y;
			if (Ypos < 0) Ypos = 0;
			chooser.innerHTML = txt;
			chooser.style.top = Ypos+"px";
			chooser.style.height = (Y+2)+"px";
			chooser.style.left = Xpos+"px";
			chooser.style.visibility = "visible";
		};

		mkt.holder.popdownAndBet = function(marketID, outcomeID, bookieID)
		{
			var chooser = RPOST.applet.bookieChooser;
			if (chooser == null) return;
			var _this = this;
			
			if (document.removeEventListener)
			{
				top.removeEventListener("mousedown", this.e1 , false);
				chooser.removeEventListener("mousedown", this.e2, false);
			}
			else if (top.detachEvent)
			{
				top.document.detachEvent("onmousedown", this.e1);
				chooser.detachEvent("onmousedown", this.e2);
			}
			chooser.style.visibility = "hidden";
			if (marketID == null) return;
			this.Bet(marketID, outcomeID, bookieID);
		};
	} // end of setupRenderAsRicegrains
}; // end of RPOST.applet namespace
// load Applet Transport Layer
(function (){RPOST.applet.toolkit.loadATL();})();
//} // end of if(RPOST.applet...


