// $Id: betslipheader.js,v 1.1.2.130 2010-08-19 11:26:54 tmacdona Exp $

// This file contains javascript functions that are required by the betslip.
// These functions may be called before the betslip is actually opened.
//
// The naming convention is that functions and globals in this file should be
// prefixed with "BS_".

// minified CVS tag version
var dummy = '$Id: betslipheader.js,v 1.1.2.130 2010-08-19 11:26:54 tmacdona Exp $';

// Holds information for leg construction.
var BS_LEG = new Array();

var EXTRAINFO = new Array();

function BS_set_extra_info(name, value) {
	EXTRAINFO[name] = value;
}

function BS_get_extra_info(p_name) {
	return (EXTRAINFO[p_name]) ? EXTRAINFO[p_name] : '';
}

// Set a parameter of the current leg
function BS_set_leg(name, value) {
	BS_LEG[name] = value;
}

// Get the current leg parameter value (associated to its parameter name)
// Returns '' if non specified
//
function BS_get_leg(p_name) {
	return (BS_LEG[p_name]) ? BS_LEG[p_name] : '';
}

// Returns the default leg format. This is stored in the leg_format_cookie
// This is required by the betslip in order to generate leg for a given bet.
//
function BS_get_leg_format() {
	return get_cookie(betslipheader.cookie_name.LEGFORMAT).split('|');
}

// Update the "bet count" value displayed in the betslip header
//
function BS_upd_bet_count(num) {

	var myBetCountElement = document.getElementById('bsCounter');

	if (myBetCountElement) {
		if (num > 1) {
			myBetCountElement.innerHTML = betslipheader.msg.BS_SELECTIONS + num;
		} else {
			myBetCountElement.innerHTML = betslipheader.msg.BS_SELECTION + num;
		}
	}

	document.forms['betslipCount'].bet_count.value = num;
}


// Does the user appear to be looking at the bet receipt (based on his cookie)?
function BS_is_on_receipt() {
	var cookie_str = get_cookie(betslipheader.cookie_name.RECEIPT);
	return (cookie_str != null && cookie_str.length > 0);
}


// Clear the bet receipt cookie.
function BS_clear_receipt_cookie() {
	set_cookie(
	  betslipheader.cookie_name.RECEIPT, '',
	  '', betslipheader.cookie_path, '', '');
}


// Clear the bet slip selection cookie
function BS_clear_seln_cookie() {
	set_cookie(
	  betslipheader.cookie_name.LEG, '',
	  '', betslipheader.cookie_path, '', '');
}


// Clear the bet slip.
//
function BS_clear_bet_slip() {
	BS_upd_bet_count(0);
	BS_clear_seln_cookie();
	BS_upd_betslip();

	//Clear fast bet stuff
	set_cookie("FASTBET_PROCESS","","","/");
	BS_clear_fastbet_cookie();
}


// Add a selection to the betslip.
// This function clears the contents of BS_LEG
//
function BS_go_bet (fast_bet) {

	// Clear fasbet cookies when adding selns
	// and we are not in a fastbet
	var bir_req_id = get_cookie("BIR_REQ_ID");
	var possible_placed_bet = get_cookie("POSSIBLE_PLACED_BET");
	if (!fast_bet && (BS_is_on_receipt() || (bir_req_id == "" && possible_placed_bet == ""))) {
		set_cookie("FASTBET_PROCESS","","","/");
		BS_clear_fastbet_cookie();
	}

	if (BS_is_on_receipt()) {
		// If the user is adding a selection, we must clear his bet
		// receipt cookie. We assume he doesn't want to keep the
		// selections on the receipt (arguably we should examine his
		// retain selection tick box, but that's rather fiddly).
		BS_clear_receipt_cookie();
		// We don't want to clear the betslip cookie if we are in a fast bet
		if (!fast_bet) BS_clear_seln_cookie();
	}

	if (BS_selection_limit(1)) {
		BS_LEG = new Array();
		return;
	}

	var leg = '';
	var last_selection = '';
	var leg_params = BS_get_leg_format();

	
	leg_params.each(function(item) {
		var v = BS_get_leg(item);
		if (v.length) {
			// Map pipes to colons within the non-null leg params to avoid
			// clashing with our separator.
			v = v.replace(/\|/g, ':')
		}		
		leg += '|' + item + '~' + v;
		
		if(item == "selections"){
			last_selection = v;
		}
	});

	leg = '&leg=' + leg.substring(1);

	// Clear BS_LEG info
	BS_LEG = new Array();

	var bs_style = get_pref('BETSLIP_STYLE');
	var url = "";
	var bet_uid = "";
	if (bs_style == 'Detached') {
		if (fast_bet) {
			disable_fastbet_buttons_upd_cookie();
			url = betslipheader.url.REMOTE_BS_URL + '&go_place_fast_bet=1&bet_uid=' + fastbet_betuid + leg;
			update_fastbet_uid();
			set_cookie("POSSIBLE_PLACED_BET","1","","/");
		} else {
			url = betslipheader.url.REMOTE_BS_URL + '&bs_add_leg_to_slip=1' + leg;
		}
		url +=  '&uid=' + get_cookie(loginuid_cookie_name);
		BS_upd_pop_out(url);
	} else {
		if (fast_bet) {
			disable_fastbet_buttons_upd_cookie();
			try {
				bet_uid = document.forms['betSlipMainForm'].elements['bet_uid'].value;
			}catch(e){
				bet_uid = fastbet_betuid;
				update_fastbet_uid();
			}
			url = betslipheader.url.CGI_URL + '?action=GoBetPlace&go_place_fast_bet=1&bet_uid=' + bet_uid + leg ;
			set_cookie("POSSIBLE_PLACED_BET","1","","/");
		} else {
			url = betslipheader.url.CGI_URL + '?action=GoBetAdd' + leg ;
		}
		url += '&uid=' + get_cookie(loginuid_cookie_name);
		BS_view_betslip(url);
	}

	if(typeof(netinsight) != "undefined"){
		if(netinsight){
			//add event here!!
			ntptAddPair("bsa",last_selection);
			ntptEventTag("ev=addtobetslip");
		}
	}
}


function update_fastbet_uid() {

	// Make Ajax call to re-generate fastbet_betuid
	var url = betslipheader.url.CGI_URL + '?action=go_update_fastbet_betuid';
	new Ajax.Request(url, {
		method: 'get',
			onSuccess: function(transport) {
				fastbet_betuid = transport.responseText;
			},
			onException: function(req, exception) {
				//alert(exception);
			}
		});
}

// Updates the betslip header selections count using a hidden input
// value stored in the betslip body. Returns num selns.
function BS_upd_bet_count_from_slip () {

	var count = 0;

	var num_selns_elem = document.getElementById("num_selns");
	if (num_selns_elem) {
		count = num_selns_elem.value;
	}

	BS_upd_bet_count(count);

	return count;
}



// This array is used to keep track of the bets that have been selected
// within the page (prior to adding them to the betslip)
//
var BS_SELECTED_BETS = new Array ();

// This gets called whenever a bet is selected within the page.
// It simply adds the bet to the SELECTED_BETS array.
// It clears the contents of BS_LEG
function BS_select_bet (unique_id, group_unique_id) {
	var bet;

	// First, check if the bet is already in the SELECTED_BETS array
	var bet_exist = false;
	BS_SELECTED_BETS.each(function(item) {
		// If it is already there then flag it to be placed, and return.
		if (item['unique_id'] == unique_id) {
			item['place'] = 'Y';
			bet_exist = true;
			throw $break
		}
	});

	if (bet_exist) {
		return true;
	}

	// Set the bet to the SELECTED_BETS array
	bet = new Array();

	var leg_params = BS_get_leg_format();
	leg_params.each(function(item) {
		bet[item] = BS_get_leg(item);
	});

	// Clear BS_LEG info
	BS_LEG = new Array();

	// Unique id by which to identify the bet within the array
	bet['unique_id']  = unique_id;
	// Group that this bet belongs to.  Sometimes we only want to add a given
	// group of selected bets to the betslip, rather than all the selected ones.
	bet['group_unique_id'] = group_unique_id;
	// Flag indicating whether this bet should be placed or not
	bet['place']      = 'Y';

	BS_SELECTED_BETS.push(bet);
}



// Clear all bets belonging to the given group from the BS_SELECTED_BETS array.
// If no group is given then clear all bets from the array.
//
function BS_deselect_all_bets (group_unique_id) {
	if (group_unique_id) {
		BS_SELECTED_BETS.each(function(item) {
			if (item['group_unique_id'] == group_unique_id) {
				item['place'] = 'N';
			}
		});
	} else {
		BS_SELECTED_BETS = new Array ();
	}
}



// This gets called whenever the "bet now" (or equivalent) button is clicked
// within the page.  It submits a request to add all of the bets in
// BS_SELECTED_BETS which match the given group_unique_id to the betslip.
// If no group is specified then it adds all of the bets in BS_SELECTED_BETS
//
function BS_go_bets (group_unique_id) {
	var bet;
	var url = '';
	var leg_params = BS_get_leg_format();
	var last_selection = '';

	if (BS_is_on_receipt()) {
		// If the user is adding a selection, we must clear his bet
		// receipt cookie. We assume he doesn't want to keep the
		// selections on the receipt (arguably we should examine his
		// retain selection tick box, but that's rather fiddly).
		BS_clear_receipt_cookie();
		BS_clear_seln_cookie();
	}

	if (BS_selection_limit(BS_SELECTED_BETS.length)) {
		BS_deselect_all_bets(group_unique_id);
		return;
	}

	BS_SELECTED_BETS.each(function(bet_item) {

		// Skip over bets that are flagged not to be placed.
		if (bet_item['place'] != 'Y') {
			//since the block is a function, return as the same effect as continue
			return;
		}

		// Skip over bets that aren't in the given group
		if (group_unique_id && bet_item.group_unique_id != group_unique_id) {
			return;
		}

		var leg = '';
		leg_params.each(function(leg_item) {
			leg += '|' + leg_item + '~' + bet_item[leg_item];

			if (leg_item == "selections") {
				last_selection = bet_item[leg_item];
			}
		});

		url += '&leg=' + leg.substring(1);

		if(typeof(netinsight) != "undefined"){
			if(netinsight){
				//add event here!!
				ntptAddPair("bsa",last_selection);
				ntptEventTag("ev=addtobetslip");
			}
		}
	});
	
	var acc_stake = BS_get_extra_info("acc_stake");
	
	if (acc_stake != "") {
		url = url + "&acc_stake=" + acc_stake;
	}
	
	var bettype_stake = BS_get_extra_info("bettype_stake");
	
	if (bettype_stake != "") {
		url = url + "&bettype_stake=" + bettype_stake;
	}
	
	BS_deselect_all_bets(group_unique_id);

	var bs_style = get_pref('BETSLIP_STYLE');
	if (bs_style == 'Detached') {
		url = betslipheader.url.REMOTE_BS_URL + '&bs_add_leg_to_slip=1' + url;
		BS_upd_pop_out(url);
	} else {
		var params = 'action=GoBetAdd' + url;
		BS_view_betslip(betslipheader.url.CGI_URL,params);
	}
}



// open the betslip
//
function BS_view_betslip(url,params) {
	if (!params) params='';
	BS_load_betslip(url,'POST',params);
	BS_open_betslip();
}



// Open the betslip (and update the betslip status cookie)
//
function BS_open_betslip() {

	// Change the img/action
	var toggle_link = document.getElementById('toggleLink');
	if (toggle_link) {
		toggle_link.href = 'javascript:BS_close_betslip()';
		toggle_link.className = 'minimise';
	}

	// Make betslip visible
	var bs = document.getElementById('betSlipBodyMembrane');
	bs.style.display = '';
	// Make popout / pop back link visible
	var po = document.getElementById("popout");
	if (po != null) {
		po.style.display = 'block';
	}

	// Update status cookie
	if (get_pref('bs_minimized')!= 0) {
		set_pref('bs_minimized', '0');
	}

	var bsb = document.getElementById("bsScroller");
	bsb.style.position = '';
	position_betslip();
}



// Close the betslip (and update the betslip status cookie)
//
function BS_close_betslip() {

	// Change the img/action
	var toggle_link = document.getElementById('toggleLink');
	if (toggle_link) {
		toggle_link.href = 'javascript:BS_open_betslip()';
		toggle_link.className = 'maximise';
	}

	// Make betslip invisible
	var bs = document.getElementById('betSlipBodyMembrane');
	bs.style.display = 'none';

	var po = document.getElementById("popout");
	if (po != null) {
		if(get_pref('BETSLIP_STYLE') == 'Detached'){
			po.style.display = 'block';
		} else {
			po.style.display = 'none';
		}
	}

	// Update status cookie
	if (get_pref('bs_minimized')!= 1) {
		set_pref('bs_minimized', '1');
	}

	var bsb = document.getElementById("bsScroller");
	bsb.style.position = 'absolute';
	position_betslip();
}

// This function position the betslip within the page
//
function position_betslip(){
	var bshl = document.getElementById("bsHeaderLeft");
	var bshr = document.getElementById("bsHeaderRight");
	var bsb = document.getElementById("bsScroller");
	var bsOA = document.getElementById("bsOpenAnchor");

	if (!bsb) return;

	var bswidth = 228;
	var absleft = 1000 - bswidth;
	var myWidth, scrollTop;

	if (document.documentElement && document.documentElement.clientWidth != 0) {
		scrollTop = document.documentElement.scrollTop;
		myWidth = document.documentElement.clientWidth;
	} else {
		scrollTop = document.body.scrollTop;
		myWidth = document.body.clientWidth;
	}


	if (get_pref('BETSLIP_STYLE') != 'Detached') {

		if (bsOA) bsOA.style.display = "none";

		if ((myWidth > 1000 + bswidth) && get_pref('bs_minimized') != '1' && get_pref('bs_minimized') != null) {
			bsb.style.left = "1001px";
			//bsb.style.top = (132 + scrollTop) + "px";
			bshr.style.backgroundImage = "url(//i.ppstatic.com/img/betslip/bshead-r.gif)";
			if(bshl) bshl.style.display = "block";

		} else {
			bsb.style.left = absleft + "px";
			//bsb.style.top = (132 + scrollTop) + "px";
			bshr.style.backgroundImage = "url(//i.ppstatic.com/img/betslip/bshead.gif)";
			if(bshl) bshl.style.display = "none";
		}
	} else {
		bsb.style.left = "0px";
		bsb.style.top = "33px";
		if (bshl) bshl.style.display = "block";
		if (bsOA) bsOA.style.display = "inline";
	}
	//alert(get_pref('bs_minimized'));
	vsize_betslip();
}

function vsize_betslip(is_popout){
	var bs = document.getElementById("bsScroller");
	var bscroll = document.getElementById("betSelectionsScroll");
	var oscroll = document.getElementById("optionsScroll");
	var h = 0;
	
	var isIE = false;
	if (document.documentElement && document.documentElement.clientHeight != 0) {
		h = document.documentElement.clientHeight;
		isIE = true;
	} else {
		h = document.body.clientHeight;
	}
	var solidheight = 300; //"solid" = parts of the betslip that don't scroll + bs.style.top
	var singlebetheight = 40;
	var singleoptionheight = 30;


	if(document.getElementById("is_receipt") != null){
		solidheight = 490;
		singlebetheight = 72;
		singleoptionheight = 95;
	}
	
	if(document.getElementById("is_bir_confirm") != null){
		singlebetheight = 70;
	}

	if(get_pref('BETSLIP_STYLE') == 'Detached'){
		solidheight -= 105;
	}

	var betshare, optionshare, bscrollshare, oscrollshare;
	betcount = 0;
	optioncount = 0;
	optionshare = 0;
	bscrollshare = 0;
	oscrollshare = 0;
	
	if(bscroll != null){
		var bets = bscroll.getElementsByTagName("tr");
		for(var b=0;b<bets.length;b++){
			if(bets[b].className == "bselection" || bets[b].className == "suspended"){
				betcount++;
			}
		}
		// APPROXIMATE height of selections div. Doesn't need to be perfect as long as options
		// div below is calculated the same way; relative proportions are what count here
		betshare = betcount * singlebetheight;


		if(oscroll != null){
			var options = oscroll.getElementsByTagName("tr");
			for(var o=0;o<options.length;o++){
				if(options[o].className == "boption"){
					optioncount++;
				}
			}
			optionshare = optioncount * singleoptionheight;
		}


		var totalshare = h - solidheight;
		bscrollshare = Math.floor(totalshare * (betshare/(betshare + optionshare)));
		//alert(bscrollshare + "= Math.floor(" + totalshare + "* (" + betshare + "/(" + betshare + "+" + optionshare + "))");
		oscrollshare = (totalshare - bscrollshare);
		//introduce scroll
		//alert("betslip = " + (bs.clientHeight + 135) + " and window = " + h);
		if(betcount > 0 && (parseInt(135 + bs.clientHeight) > h|| bscroll.style.overflowY == "auto")){
			bscroll.style.height = bscrollshare + "px";
			bscroll.style.overflowY = "auto";
			//alert(bscroll.style.overflowY);
			if(isIE == true){
				document.getElementById("betSelections").style.width = "202px";
			}
			bscroll.style.zIndex = "0";
			if(document.getElementById("selectionHead") != null){
				document.getElementById("selectionHead").style.width = "70px";
			}
			//alert (optionshare + " " + oscrollshare);
			if(optionshare > oscrollshare){
				oscroll.style.height = oscrollshare + "px";
				oscroll.style.overflowY = "auto";
				if(isIE == true){
					document.getElementById("options").style.width = "202px";
				}
				oscroll.style.zIndex = (parseInt(bscroll.style.zIndex) -1);
				if(document.getElementById("optionHead") != null){
					document.getElementById("optionHead").style.width = "113px";
				}
			}
		}



		//back to normal
		if(bscroll.scrollHeight <= bscroll.clientHeight){
			if(betcount == 1){
				if(document.getElementById("is_receipt") != null){
					//alert("receipt");
					bscroll.style.height = "auto";
				}else{
					//alert("not receipt");
					bscroll.style.height = (betshare * 2) + "px";
					if(betcount==1){
						if(document.getElementById("gp_div") != null){
							bscroll.style.height = "auto";
						}
					}
				}
			}else{
				bscroll.style.height = "auto";
			}
			bscroll.style.overflowY = "";
			if(isIE == true){
				document.getElementById("betSelections").style.width = "";
			}
			if(document.getElementById("selectionHead") != null){
				document.getElementById("selectionHead").style.width = "";
			}
			if(oscroll != null){
				oscroll.style.height = "auto";
				oscroll.style.overflowY = "";
				if(isIE == true){
					document.getElementById("options").style.width = "";
				}
				if(document.getElementById("optionHead") != null){
					document.getElementById("optionHead").style.width = "";
				}
			}
		}else{
			//alert("no expand");
		}
		//alert("window = " + h + ", betslip = " + bs.clientHeight + "\n" + betshare + ":" + optionshare + "\nshared " + totalshare + " as " + bscrollshare + ":" + oscrollshare);
	}
}



// Updates the content of the Popped out betslip
//
function BS_upd_pop_out(url) {

	popped_out_betslip = window.open(url, betslipheader.popup_name, 'width=300,scrollbars=1,resizable=1,status=1');
	popped_out_betslip.focus();

	var fb_process = get_cookie('FASTBET_PROCESS');

	//Loading bar when processing fast bet
	if (get_pref('BETSLIP_STYLE') == "Detached" && fb_process && fb_process == '1') {
		// Sometimes the remote betslip is not loaded yet (because we closed the
		// window before), so it can cause a js error
		try {
			var status_area = popped_out_betslip.document.getElementById('bsCounter');
			if (status_area) {
				status_area.innerHTML = "<img src='/img/betslip/loadbar.gif' style='width:90px;padding:4px 0' />";
			}
		} catch (e) {}
	}
}



// Pops out the betslip
//
function BS_pop_out(url_arg) {

	var fb_process = get_cookie('FASTBET_PROCESS');

	//People shouldn't be doing this while
	//processing a fastbet so be clear the
	//cookie and enable the buttons back
	if(fb_process && fb_process == '1') {
		BS_clear_fastbet_cookie();
		enable_fastbet_buttons_upd_cookie();
	}

	// open the betslip window
	var url = betslipheader.url.REMOTE_BS_URL;
	if (url_arg) {
		url = url + "&" + url_arg;
	}
	BS_upd_pop_out(url);

	// updates the cookie
	set_pref('BETSLIP_STYLE', 'Detached');

	// make betslip invisible
	var bs = document.getElementById('bsScroller');
	var bshl = document.getElementById('bsHeaderLeft');
	var bsOA = document.getElementById('bsOpenAnchor');
	if (bs != null) {
		bs.style.display = 'none';
		if (bshl) bshl.style.display = 'none';
	}

	if (bshl) bshl.style.display = 'block';
	if (bsOA) bsOA.style.display = 'inline';
}



// Pop back the betslip (called from popup betslip).
//
var opener_window;
function BS_pop_back() {

	// update the cookie
	set_pref('BETSLIP_STYLE', 'Attached');

	// tell the parent page to show the inline betslip
	// (this is a little tricky if it's https or no longer exists)

	// The name which we expect the main PPW window to have.
	var main_win_name = 'ppmain';
	// Used if we cannot simply refresh the main window.
	var fallback_url  = betslipheader.url.CGI_URL;
	// Used if we have to create a new main window.
	var win_features  = 'scrollbars=1,resizable=1,location=1,menubar=1,status=1,titlebar=1,toolbar=1';

	// See later ...
	if (!opener_window) {
		opener_window = window.opener;
	}

	// What's the name of the window which opened us?
	var opener_name;
	try {
		opener_name = opener_window.name;
	} catch (e) {
		opener_name = 'unknown'
	}

	// If we're coming from the betlive medicentre, we want the window
	// that opened the window the mediacentre (the opener of the opener)
	if (opener_name == 'PP_MediaCentre') {
		opener_window = opener_window.opener;
		// Need to redo the name or else the below code won't work properly
		try {
			opener_name = opener_window.name;
		} catch (e) {
			opener_name = 'unknown'
		}
	}

	// Is the window which opened us still present?
	// NB - It seems to be safe to do this even if the opener is using
	// a different protocol.
	if (!opener_window) {
		opener_closed = true;
	} else {
		opener_closed = opener_window.closed;
	}

	if (opener_closed) {
		// Opener has closed - need to open new main window.
		// This does mean that it's no longer our opener - that's why we
		// have the opener_window global.
		opener_window = window.open(fallback_url, main_win_name, win_features);
	} else if (opener_name != main_win_name) {
		if (opener_name == 'unknown') {
			// The opener is using a different protocol (most likely it's https
			// whereas we are http).
			// We can't execute javascript in it, and we probably don't want to
			// reload it, so we'll go to the fallback url. I *think* we can
			// still change its location.
			opener_window.location = fallback_url;
		} else {
			// Opener was not PPW (perhaps a 3rd party) - need to open new
			// main window.
			// This does mean that it's no longer our opener - that's why we
			// have the opener_window global.
			opener_window = window.open(fallback_url, main_win_name, win_features);
		}
	} else {
		// Our opener is the ppw main window and on the same protocol.
		if (opener_window.location.protocol.startsWith('https')) {
			// However, we don't want to reload an HTTPS page...
			opener_window.location = fallback_url;
		} else {
			// We tell it to pop back in by reloading it (this may change in future).
			opener_window.location.reload();
		}
	}

	// close the betslip window
	window.close();

}


// Open the given url in the main window (called from popup betslip).
//
var opener_window = null;
function BS_open_in_main(url) {

	// The name which we expect the main PPW window to have.
	var main_win_name = 'ppmain';
	// Used if we have to create a new main window.
	var win_features  = 'scrollbars=1,resizable=1,location=1,menubar=1,status=1,titlebar=1,toolbar=1';

	// See later ...
	if (!opener_window) {
		opener_window = window.opener;
	}

	// What's the name of the window which opened us?
	var opener_name;
	try {
		opener_name = opener_window.name;
	} catch (e) {
		opener_name = 'unknown'
	}

	// Is the window which opened us still present?
	// NB - It seems to be safe to do this even if the opener is using
	// a different protocol.
	if (!opener_window) {
		opener_closed = true;
	} else {
		opener_closed = opener_window.closed;
	}

	if (opener_closed) {
		// Opener has closed - need to open new main window.
		// This does mean that it's no longer our opener - that's why we
		// have the opener_window global.
		opener_window = window.open(url, main_win_name, win_features);
	} else if (opener_name != main_win_name) {
		if (opener_name == 'unknown') {
			// The opener is using a different protocol (http vs https).
			// I *think* we can still change its location.
			opener_window.location = url;
		} else {
			// Opener was not PPW (perhaps a 3rd party) - need to open new
			// main window.
			// This does mean that it's no longer our opener - that's why we
			// have the opener_window global.
			opener_window = window.open(url, main_win_name, win_features);
		}
	} else {
		// Our opener is the ppw main window and on the same protocol.
		// We can simply change its location.
		opener_window.location = url;
	}

}


// Start the registration process from the betslip popup.
//
var opener_window = null;
function BS_go_register_from_popup(inline,unicatag) {

	if (!opener_window) {
		opener_window = window.opener;
	}

	if (typeof unicatag == 'undefined') {
		var unicatag = 0
	}

	try {
		// Try to make the main window bring up the reg popup so
		// that the choose deposit page appears in the right window.
		if (unicatag) {
			var unicabutton = "betslipregbutton";
		} else {
			var unicabutton = '';
		}
		if (inline) {
			opener_window.go_register_inline(bus_channel,unicabutton);
		} else {
			opener_window.go_register(bus_channel,unicabutton);
		}
	} catch (e) {
		var reg_url = betslipbody.url.SCGI_URL;
		var area;
		reg_url += '?action=go_register_popup&crea=img';
		reg_url += '&bus_channel=' + bus_channel;
		if (bus_channel == '') {
			area = "SB";
		} else {
			area = bus_channel;
		}
		if (unicatag) {
			reg_url += '&area=' + area + '&button=betslipregbutton';
		}
		location.replace(reg_url);
		//window.innerHeight = 640;
		//window.innerWidth = 662;
		window.resizeTo(640,662);
		// XXX Not sure what to do here - presumably the main window
		// is closed, HTTPS, or not PaddyPower's window.
		// If we open the reg popup ourselves, it won't know how to make
		// the choose deposit page appear in the main window.
		// We could try to do a BS_open_in_main so that we then control
		// the main window, and tell it to do the go_register, but that
		// seems to get stopped by popup blockers.
	}

	return false;
}


// Load the betslip by submitting a given form
//
// Second parameter is optional and replaces the form's action URL.
// e.g. You might want to use this if the form is https but you want to
//      submit via http instead.
//
// Optionally set some request parameters before submitting the form
//
// Alternatively, see:  BS_load_betslip()
//
function BS_submit_betslip(form,url) {
	var f = document.forms[form];

	// To find the form's action and method, we create a clone of the form
	// element to get around problems where there may be input elements called
	// 'action' or 'method'
	var fc = f.cloneNode(false);
	if (!url || url == '') var url = fc.action;
	var method=fc.method;

	// If extra arguments have been supplied, set the corresponding input
	// element values of the form.
	// e.g. BS_submit_betslip('betSlipDeleteLegForm','','legs','123') would
	// find an input element called 'legs' and set its value to '123'
	// before submitting the form.
	if (arguments.length > 2) {
		for (var i=2; i<arguments.length; i+=2) {
			f.elements[arguments[i]].value = arguments[i+1];
		}
	}

	var ok=BS_submit_betslip_xmlhttprequest(url,getFormContent(form),method);
	if (!ok) {
		//alert('Browser does not support XMLHttpRequest.');
		//f.submit();
	}
}



// Called whenever the betslip area has loaded - this could have occurred
// via AJAX (in which case from_ajax will be true), or when the page
// containing the betslip loads.
function BS_req_end (from_ajax) {

	// Update the betslip header selections count
	var count = BS_upd_bet_count_from_slip();

	// Ensure that the correct element in the freebet menu is selected.
	BS_update_freebet_menu();

	// Decide which individual sections to show or hide.
	BS_init_show_hide();

	// Maximise or minimise (aka open or close) the betslip.
	var bs_minimized;
	var bs_style = get_pref('BETSLIP_STYLE');
	var fb_process = get_cookie('FASTBET_PROCESS');
	if (bs_style == 'Detached') {
		// Popup is never minimised.
		bs_minimized = false;
	} else if (fb_process && fb_process == '1') {
		//We should allow show alerts, if we have a problem
		//when processing a fast bet
		bs_minimized = false;
	} else {
		// Inline follows the minimise preference ...
		bs_minimized = (get_pref('bs_minimized') == '1');
		// ... unless we've updated the betslip via AJAX, which strongly
		// suggests something has happened which we should show the user.
		if (from_ajax) {
			bs_minimized = false;
		}
		// ... unless there's no selections, in which case
		// it minimises by default.
		if (count == 0) {
			bs_minimized = true;
		}
	}
	if (!bs_minimized) {
		BS_open_betslip();
	} else {
		BS_close_betslip();
	}

	// Setting an onload function will be ignored as the html returned from
	// the AJAX request will simply be written to the page. You can specify
	// a function to be executed on the loading of the page by setting a
	// hidden input with an id of onload_func and value of the function name
	var onload_func_elem = document.getElementById("onload_func");
	if (onload_func_elem) {
		if (onload_func_elem.value != "") {
			eval(onload_func_elem.value);
		}
	}

	// do not test if this was part of an bet placement,
	// only if we are simply displaying the slip 
	if (!from_ajax)
		BS_test_possible_placed();

	if(window.attachEvent){ieDropDownFix();}
	vsize_betslip();

	if (BS_is_on_receipt()) {
		enable_fastbet_buttons_upd_cookie();
		
		BS_refresh_my_bets();
	}

}

function BS_refresh_my_bets() {

	// this function is loaded for BIR pages only
	//
	// window.opener 		- this will be used for the popout
	// window.opener.opener - this will be used for bets placed
	//  						from the media section as we expect
	//  						to be 2 windows removed from originating
	//  						bir events page
	if(window.refresh_my_bets) {
		refresh_my_bets(1);
	} else if (window.opener) {
		if (window.opener.refresh_my_bets){
			window.opener.refresh_my_bets(1);
		} else if (window.opener.opener) {
			if (window.opener.opener.refresh_my_bets){
				window.opener.opener.refresh_my_bets(1);
			}
		}
	}
}


// Test for POSSIBLE_PLACED_BET cookie
//
function BS_test_possible_placed() {

	//A Bet MAY have been placed and the customer navigated away before being shown
	// a bet receipt or confirming bet message.

	var bir_req_id          = get_cookie("BIR_REQ_ID");
	var possible_placed_bet = get_cookie("POSSIBLE_PLACED_BET");

	if (get_cookie("POSSIBLE_PLACED_BET") == 1 && bir_req_id.match(/^[\d]+$/) == null) {
		BS_display_error(betslipheader.msg.BS_PB_WARNING_TITLE, betslipheader.msg.BS_PB_WARNING_TXT);
		document.getElementById('close_text').innerHTML = betslipheader.msg.BS_ERROR_CLOSE;
		set_cookie("POSSIBLE_PLACED_BET","","","/");

		//If we were processing a fast bet enable-back the buttons
		var fb_process = get_cookie('FASTBET_PROCESS');
		if (fb_process && fb_process == '1') {
			set_cookie("FASTBET_PROCESS","","","/");
		}

	} else if (bir_req_id.match(/^[\d]+$/) != null && playing_bir_confirm != 1) {
		// catch a case where the bir_req_id cookie has been set but the polling has not started
		BS_load_betslip(betslipbody.url.CGI_URL + '?action=GoBetSlip&retain=Y', 'POST');
	}

}

// Load the betslip with a given url into the current window.
//
// Alternatively, see:  BS_submit_betslip()
//
function BS_load_betslip(url,method,params) {
	if (!params) params='';
	if (!method) method='POST';
	url = encodeURI(url);
	BS_submit_betslip_xmlhttprequest(url, params, method);
}



// Check if the previous request was processed successfully
//
function callInProgress(xmlhttp) {
	if (!xmlhttp) {
		return false;
	}
	switch (xmlhttp.readyState) {
		case 1: case 2: case 3:
			return true;
			break;
		default:
			// Case 4 and 0
			return false;
			break;
	}
}



var req = null;
var timeoutId = null;
// Submit an XMLHttpRequest and replace the betslip html with the
// response text which should also be html
//
function BS_submit_betslip_xmlhttprequest(url,content,method) {
	
	if (req == null) {
		// Initialize XML request
		if (window.XMLHttpRequest) {
			// Firefox, Safari etc.
			req = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			// Internet Explorer
			req = new ActiveXObject('Microsoft.XMLHTTP');
		}
	}

	if (req) {
		// Define response handler for the XMLHttpRequest
		req.onreadystatechange = function() {
			if (req.readyState != 4) {
				return false;
			}
			// Clear the timeout
			window.clearTimeout(timeoutId);

			var reqStatus;
			try {
				reqStatus = req.status;
			}
			catch (e) {
				return false;
			}

			if (reqStatus != 200) {
				alert(betslipbody.msg.BS_AJAX_REQ_ERROR_TXT + "\n" + req.statusText);
				return false;
			}

			// Replace the existing betslip contents
			var betSlipBodyMembrane = document.getElementById('betSlipBodyMembrane');
			betSlipBodyMembrane.innerHTML = req.responseText;
			//document.getElementById("testme").innerHTML = req.responseText;

			// Perform any functions needed once the betslip has been reloaded
			BS_req_end(true);

			req = null;
		}

		if (!callInProgress(req)) {
			// implements a timeout
			timeoutId = window.setTimeout(function() {
				if(callInProgress(req)) {
					req.abort();
					BS_display_error(betslipheader.msg.BS_TIMEOUT_TITLE,  betslipheader.msg.BS_TIMEOUT_TXT);
					return false;
				}
			}, parseInt(betslipheader.cfg.BETSLIP_REQ_TIMEOUT));

			// Put "loading" text in betslip "status area"
			var status_area = document.getElementById('bsCounter');
			if (status_area) {
				status_area.innerHTML = "<img src='//i.ppstatic.com/img/betslip/loadbar.gif' style='width:90px;padding:4px 0' />";
			}

			req.open(method, url, true);
			req.setRequestHeader('content-type','application/x-www-form-urlencoded');
			if (betslipheader.url.HTTP_REFERER != "") {
				req.setRequestHeader("Referer", betslipheader.url.HTTP_REFERER);
			}
			req.send(content);
		} else {
			BS_display_error(betslipheader.msg.BS_LOADING,  betslipheader.msg.BETSLIP_PLEASE_WAIT);
			return false;
		}

	} else {
		// Browser does not support AJAX
		BS_display_error(betslipheader.msg.BS_UNSUPPORTED_AJAX_TITLE,  betslipheader.msg.BS_UNSUPPORTED_AJAX_TXT);
		return false;
	}
	return true;
}



// Initialise whether sections are shown or hidden.
// Should be called on page load.
//
function BS_init_show_hide() {

	// This preference contains a comma-separated list of sections which
	// should be hidden. Any other sections default to being shown.

	var bs_hide_sections = get_pref('bs_hide_sect');
	if (bs_hide_sections == null) {
		bs_hide_sections = [];
	} else {
		bs_hide_sections = bs_hide_sections.split(',');
	}

	var all_sections = [ 'selns', 'bopts' ];

	for (var i = 0; i < all_sections.length; i++) {
		var section = all_sections[i];
		var show    = (bs_hide_sections.indexOf(section) == -1);
		BS_show_section(section, show, true);
	}

	return;
}


// Show or Hide a section of the Betslip.
// Params:
//   section       - which section: 'selns' or 'bopts'
//   show          - whether to show: true to show, false to hide
//   skip_pref_upd - whether to skip storing the new setting across
//                   requests.
//
function BS_show_section(section, show, skip_pref_upd) {

	// Find the element we are mean to be showing/hiding.

	var elem_to_show;
	if (section == 'selns') {
		elem_to_show = $('betSelectionsScroll');
	} else if (section == 'bopts') {
		elem_to_show = $('optionsScroll');
	} else {
		throw 'unknown section to show: ' + section;
	}

	if (elem_to_show != null) {
		elem_to_show.style.display = show ? '' : 'none';
	}

	// If section shown, hide the show link and show the hide link
	// (and vice versa if the section is hidden of course).

	var show_link = $('bs_show_' + section + '_link');
	var hide_link = $('bs_hide_' + section + '_link');
	if (show_link != null) {
		show_link.style.display = show ? 'none' : '';
	}
	if (hide_link != null) {
		hide_link.style.display = show ? '' : 'none';
	}

	// The caller may have asked us to skip updating the preference
	// (perhaps because he knows it's already up-to-date).

	if (!skip_pref_upd) {

		// This preference contains a comma-separated list of sections
		// which should be hidden. We must update it accordingly.

		var pref_name = 'bs_hide_sect';
		var bs_hide_sections = get_pref(pref_name);
		if (bs_hide_sections == null) {
			bs_hide_sections = [];
		} else {
			bs_hide_sections = bs_hide_sections.split(',');
		}
		var hide_list_posn = bs_hide_sections.indexOf(section);

		if (show && hide_list_posn != -1) {
			bs_hide_sections = bs_hide_sections.without(section);
			set_pref(pref_name, bs_hide_sections.join(','));
		} else if (!show && hide_list_posn == -1) {
			bs_hide_sections.push(section);
			set_pref(pref_name, bs_hide_sections.join(','));
		}
	}

	position_betslip();
	return false;
}

function BS_selection_limit(n) {
	var limit = 20;

	if (limit < n) {
		var title = betslipheader.msg.BS_EXCEED_SEL_TITLE;
		var text  = BS_js_subst(
			betslipheader.msg.BS_EXCEED_SEL_TEXT,
			{seln_limit: limit}
		);

		var style = get_pref('BETSLIP_STYLE');

		if (!style || style == 'Attached') {
			BS_display_error(title, text);
			BS_open_betslip();
		} else {
			alert(text);
		}

		return true;
	}

	return false;
}



function ni_sels(){
	if(typeof(netinsight) != "undefined"){
		if(netinsight){
			var ntpt_rtc = "";
			var ntpt_rtt = 0;
			var receipts = $$('span.rb_receipt');
			var stakes = $$('span.rb_stake');
			var stk;
			for(var i=0;i<receipts.length;i++){
				stk = stakes[i].innerHTML;
				stk = stk.replace(/[^\d\.-]/g,''); //remove non-numeric characters
				ntpt_rtt += parseFloat(stk);
				ntpt_rtc += receipts[i].innerHTML + ";1;" + stk + ";";
			}
			
			NTPT_PGEXTRA += "&rtt=" + ntpt_rtt;
			NTPT_PGEXTRA += "&rtc=" + ntpt_rtc;
			//alert("&rtt=" + ntpt_rtt + "&rtc=" + ntpt_rtc);
			//alert(NTPT_PGEXTRA);
			ntptEventTag("pv=1");
		}
	}
}


function check_fastbet_buttons() {

	var fb_process = get_cookie('FASTBET_PROCESS');
	if (fb_process && fb_process == '1') {
		disable_fastbet_buttons();
	} else {
		enable_fastbet_buttons();
	}
}

function enable_fastbet_buttons_upd_cookie () {

	//This prevents to close the betslip before displaying alerts
	set_cookie("FASTBET_PROCESS","","","/");
	enable_fastbet_buttons();
}

function enable_fastbet_buttons () {

	if ( typeof bir_top_displayed_page != 'undefined' &&
	     typeof fast_bet_active != 'undefined' && fast_bet_active &&
	     (bir_top_displayed_page == 'EVENT' || bir_top_displayed_page == 'FINANCIALS') ) {
		//  DON't make this call update_bir_prefs
		//  That will cause a problem with the Ajax
		//  call and the fastbet at the same time
		betDisplayPref();
	}

}

function disable_fastbet_buttons_upd_cookie () {

	//This prevents to close the betslip before displaying alerts
	set_cookie("FASTBET_PROCESS","1","","/");
	disable_fastbet_buttons ();

}

function disable_fastbet_buttons () {

	if ( typeof bir_top_displayed_page != 'undefined' &&
	     typeof fast_bet_active != 'undefined' && fast_bet_active && 
	     (bir_top_displayed_page == 'EVENT' || bir_top_displayed_page == 'FINANCIALS') ) {
		//  DON't make this call update_bir_prefs
		//  That will cause a problem with the Ajax
		//  call and the fastbet at the same time
		betDisplayPref();
	}

}

