
// $Id: betlive.js,v 1.1.8.99 2010-04-08 09:09:52 ajefferi Exp $

// This file contains javascript functions that are required by the live betting pages.
//
// The naming convention is that functions and globals in this file should be
// prefixed with "lb_".
//
// lb_bet, lb_display_market and lb_update_market requires the following variables:
//  - betlive.event.disp_mkt_data
//      Object containing all the displayed bir_market
//  - betlive.event.disp_mkt_hash
//     hash of all the displayed bir_market
//  - betlive.event.disp_seln_hash
//     hash of all the displayed selections
//  - betlive.event.bir_json_url
//	   URL of the Bet In Running JSON server
//	- betlive.event.disp_mkts_poll_interval
//	   Time interval when we should check for updates for the displayed bir_market/selections
//	- betlive.event.avail_mkts_poll_interval
//     Time interval when we should check for updates for the available bir_market
//

// minified CVS tag version
var dummy = '$Id: betlive.js,v 1.1.8.99 2010-04-08 09:09:52 ajefferi Exp $';

// betlive related variables
var betlive = new Object();

betlive.calendar = new Object();

// betlive coupon related variables
betlive.coupon = new Object();

betlive.coupon.bir_json_url = '';
betlive.coupon.coupon_mkts_poll_interval = '10000';

// Object containing the coupon bir_market and selections
betlive.coupon.coupon_mkt_data = {"bir_market": []};

// Keep a hash of all the existing bir_market/selections
betlive.coupon.coupon_seln_hash = new Hash();
betlive.coupon.coupon_mkt_hash = new Hash();


//Financials stuff, still needed
betlive.event = new Object();
betlive.event.bir_json_url = '';
betlive.event.custcom_url = '';
betlive.event.lang = 'en';
betlive.event.until_susp_label =  "";
betlive.event.until_close_label = "";
betlive.event.opening_level_label = "";
betlive.event.opening_time_label  = "";
betlive.event.financial_indicator_red = "";
betlive.event.financial_indicator_green = "";
betlive.event.financial_indicator_no_move = "";
betlive.event.warn_threshold = 5;
betlive.event.about_to_susp_message = "";
betlive.event.about_to_close_message = "";
betlive.event.financial_ev_id = "";
betlive.event.financial_hcap_to_follow = -1;
betlive.event.financial_js_url = "";

// Implement a StringBuffer to increase performance of string
// concatenation
function StringBuffer() {
	this.buffer = [];
}

StringBuffer.prototype.append = function append(string) {
	this.buffer.push(string);
	return this;
};

StringBuffer.prototype.toString = function toString() {
	return this.buffer.join("");
};


// Add a live bet to the betslip.
function lb_bet(lp_num, lp_den, hcap, mkt_id,seln_id,stake,fast_bet) {

	// Retreive the stake from the hidden input
	if (stake == -1) {
		stake = document.getElementById(seln_id).value
	}

	// Get the selection leg parameter
	var mkt_idx  = betlive.event.disp_mkt_hash.get(mkt_id);
	var seln_idx = betlive.event.disp_seln_hash.get(seln_id);

	if (mkt_idx != undefined && seln_idx != undefined) {
		BS_set_leg('price_type','L');
		BS_set_leg('stake',stake);
		//BS_set_leg('lp_num',betlive.event.disp_mkt_data.bir_market[mkt_idx].selection[seln_idx].lp_num);
		//BS_set_leg('lp_den',betlive.event.disp_mkt_data.bir_market[mkt_idx].selection[seln_idx].lp_den);
		BS_set_leg('lp_num',lp_num);
		BS_set_leg('lp_den',lp_den);
		BS_set_leg('selections',betlive.event.disp_mkt_data.bir_market[mkt_idx].selection[seln_idx].id);
		if(hcap != "") {
			BS_set_leg('hcap_value',hcap);
		} else {
			BS_set_leg('hcap_value',betlive.event.disp_mkt_data.bir_market[mkt_idx].hcap_value);
		}
		BS_set_leg('bir_index',betlive.event.disp_mkt_data.bir_market[mkt_idx].bir_index);
		BS_set_leg('market_tags',betlive.event.disp_mkt_data.bir_market[mkt_idx].tags);

		// Check fast_bet param
		var fb = typeof fast_bet === 'boolean' && fast_bet;

		BS_go_bet(fb);
	}

}

// Add a currently live bet to the betslip.
function lb_bet_curr_live(lp_num, lp_den, hcap, mkt_id,seln_id,stake,fast_bet) {

	// Retreive the stake from the hidden input
	if (stake == -1) {
		stake = document.getElementById(seln_id).value
	}

	// Get the selection leg parameter
	var mkt_idx  = betlive.event.currently_live_mkt_hash.get(mkt_id);
	var seln_idx = betlive.event.currently_live_seln_hash.get(seln_id);

	if (mkt_idx != undefined && seln_idx != undefined) {
		BS_set_leg('price_type','L');
		BS_set_leg('stake',stake);
		//BS_set_leg('lp_num',betlive.event.currently_live_mkt_data.bir_market[mkt_idx].selection[seln_idx].lp_num);
		//BS_set_leg('lp_den',betlive.event.currently_live_mkt_data.bir_market[mkt_idx].selection[seln_idx].lp_den);
		BS_set_leg('lp_num',lp_num);
		BS_set_leg('lp_den',lp_den);
		BS_set_leg('selections',betlive.event.currently_live_mkt_data.bir_market[mkt_idx].selection[seln_idx].id);
		if(hcap != "") {
			BS_set_leg('hcap_value',hcap);
		} else {
			BS_set_leg('hcap_value',betlive.event.currently_live_mkt_data.bir_market[mkt_idx].hcap_value);
		}
		BS_set_leg('bir_index',betlive.event.currently_live_mkt_data.bir_market[mkt_idx].bir_index);
		BS_set_leg('market_tags',betlive.event.currently_live_mkt_data.bir_market[mkt_idx].tags);

		// Check fast_bet param
		var fb = typeof fast_bet === 'boolean' && fast_bet;

		BS_go_bet(fb);
	}

}

// Update the coupon bir_market
function lb_update_coupon_mkts (updated_coupon_mkt_data) {

	var mkt_idx = -1;
	var seln_idx = -1;
	var has_new_selection = false;
	var updated_market = '';
	var updated_seln = '';
	var num_mkts = updated_coupon_mkt_data.bir_market.length;

	// reset the classes of price notifications
	var elements = $$('td.sltcn-txt-coupon-odds_i');
	for (i=0; i < elements.length; i++) {
		elements[i].className = 'ltcn-txt-coupon-odds';
	}
	var elements = $$('td.sltcn-txt-coupon-odds_d');
	for (i=0; i < elements.length; i++) {
		elements[i].className = 'sltcn-txt-coupon-odds';
	}

	for (var i=0; i < num_mkts; i++) {
		updated_market = updated_coupon_mkt_data.bir_market[i];
		mkt_idx = betlive.coupon.coupon_mkt_hash.get(updated_market.id);
		if (mkt_idx >= 0) {
			var mkt_id = updated_market.id;

			var num_selns = updated_market.selection.length;
			for (var j=0; j < num_selns; j++) {
				updated_seln = updated_market.selection[j];
				seln_idx = betlive.coupon.coupon_seln_hash.get(updated_seln.id);

				if(seln_idx >= 0) {
					var seln_id = updated_seln.id;
					// Check if the odds updates
					// old_lp_num    new_lp_num
					// ---------- >  -------  iff (old_lp_num * new_lp_den) > (new_lp_num * old_lp_den)
					// old_lp_den    new_lp_den             (tmp_a)         >        (tmp_b)
					var old_lp_num = betlive.coupon.coupon_mkt_data.bir_market[i].selection[j].lp_num;
					var old_lp_den = betlive.coupon.coupon_mkt_data.bir_market[i].selection[j].lp_den;
					var tmp_a = old_lp_num * updated_seln.lp_den;
					var tmp_b = old_lp_den * updated_seln.lp_lp_num;
					if (tmp_a > tmp_b) {
						document.getElementById('td_border_odds_'+seln_id).className = 'sltcn-txt-coupon-odds_i';
					} else if (tmp_b > tmp_a) {
						document.getElementById('td_border_odds_'+seln_id).className = 'sltcn-txt-coupon-odds_d';
					} else {
						document.getElementById('td_border_odds_'+seln_id).className = 'sltcn-txt-coupon-odds';
					}
					// Get price string.
					var price_str = format_price(updated_seln.lp_num,updated_seln.lp_den);
					// Update price
					document.getElementById('a_price_'+seln_id).innerHTML = price_str;
					document.getElementById('s_price_'+seln_id).innerHTML = price_str;

					if (updated_seln.status == 'S' || updated_market.status == 'S') {
						document.getElementById('a_price_'+seln_id).style.display = 'none';
						document.getElementById('s_price_'+seln_id).style.display = '';
					} else {
						document.getElementById('a_price_'+seln_id).style.display = '';
						document.getElementById('s_price_'+seln_id).style.display = 'none';
					}

					if (updated_seln.hcap_value != '' && document.getElementById('hcap_'+seln_id) != null) {
						document.getElementById('hcap_'+seln_id).innerHTML = updated_seln.hcap_value;
					}
				} else {
					has_new_selection = true;
				}
			}

			// Update the market coupon_mkt_data with the new updated values
			betlive.coupon.coupon_mkt_data.bir_market[mkt_idx] = updated_market;

			// Updates the coupon_seln_hash
			if(has_new_selection) {
				//This should not happen but update the array/hash anyway
				for (var s_index = 0, s_len = updated_market.selection.length; s_index < s_len; ++s_index) {
					updated_seln = updated_market.selection[s_index];
					betlive.coupon.coupon_seln_hash.set(updated_seln.id,s_index);
				}
			}
		} else {
			//This should only happen the first time this is called
			// New market, adds it to coupon_mkt_data
			betlive.coupon.coupon_mkt_data.bir_market.push(updated_market);

			// Updates the market hash
			betlive.coupon.coupon_mkt_hash.set(updated_market.id,(betlive.coupon.coupon_mkt_data.bir_market.length - 1));

			// Updates the selection hash
			for (var s_index = 0, s_len = updated_market.selection.length; s_index < s_len; ++s_index) {
				updated_seln = updated_market.selection[s_index];
				betlive.coupon.coupon_seln_hash.set(updated_seln.id,s_index);
			}
		}
	}
}


// Polls for bir_market updates at regular interval
function lb_auto_coupon_mkts_poll() {
	var poll_interval = betlive.coupon.coupon_mkts_poll_interval * betlive_poll_factor;
	if (poll_interval > betlive_min_poll_interval) {
		setInterval('lb_coupon_mkts_poll_server()',poll_interval);
	}
}

// Polls the BIR JSON server for bir_market update
function lb_coupon_mkts_poll_server() {

	var url = betlive.coupon.bir_json_url + '?action=bir_markets&mkt_ids=';
	var num_mkts = betlive.coupon.coupon_mkt_data.bir_market.length;

	if (num_mkts > 0) {
		url   = url + betlive.coupon.coupon_mkt_data.bir_market[0].id;
		var hash_req_param = '&hash=' + betlive.coupon.coupon_mkt_data.bir_market[0].hash;
		for (var i = 1; i < num_mkts; i++) {
			url   = url + '|' + betlive.coupon.coupon_mkt_data.bir_market[i].id;
			hash_req_param = hash_req_param + '|' + betlive.coupon.coupon_mkt_data.bir_market[i].hash;
		}
	} else {
		return;
	}
	url = url + hash_req_param;
	new Ajax.Request(url, {
	  method: 'get',
	  onSuccess: function(transport) {
		// Updates the coupon_mkts_data structure and the page display
		// with the new updates
		var json = transport.responseText.evalJSON();
		lb_update_coupon_mkts(json);
	  }
	});

}

//
// Media Center functions
//
function switchTab(tabNo) {
	// First, highlight the selected tab, and de-select the previous choice.
	var menuItems = document.getElementById('tab-list').getElementsByTagName('li');
	for (i=0; i<menuItems.length; i++) {
		if (i == tabNo) {
			menuItems[i].className = 'active';
		}
		else if (menuItems[i].className == 'active') {
			menuItems[i].className = '';
		}
	}
	// Display the correct events list, and hide the rest
	for (var id=0;id<betlive.calendar.num_tabs;id++ ) {
		if (id == tabNo) {
			document.getElementById("tab".concat(id)).style.display = 'block';
		}
		else {
			document.getElementById("tab".concat(id)).style.display = 'none';
		}
	}
}


// Find out which tab is currently selected.
function getSelectedTab() {
	var tabNo = -1;
	var menu = document.getElementById('tab-list');
	if (!menu) return tabNo;
	var menuItems = menu.getElementsByTagName('li');
	for (var i=0; i<menuItems.length; i++) {
		if (menuItems[i].className == 'media-schedule-tab-white') {
			tabNo = i;
			break;
		}
	}
	return tabNo;
}

// Check if a tab is available for selection.
function getTabAvail(tabNo) {
	var menu = document.getElementById('tab-list');
	if (!menu) return false;
	var menuItems = menu.getElementsByTagName('li');
	var items = menuItems[tabNo].getElementsByTagName("font");
	if (items.length > 0) {
		return false;
	} else {
		return true;
	}
}

function toggleFilter() {
	if (document.getElementById('event_off').style.display != 'none') {

		document.getElementById('event_off').style.display = 'none';
		document.getElementById('event_on').style.display = '';

		document.getElementById('stream_on').style.display = 'none';
		document.getElementById('stream_off').style.display = '';
		showEvents(false);
	}
	// else show streaming events only
	else {
		document.getElementById('event_on').style.display = 'none';
		document.getElementById('event_off').style.display = '';

		document.getElementById('stream_off').style.display = 'none';
		document.getElementById('stream_on').style.display = '';
		showEvents(true);
	}
}


function showEvents(streamOnly) {

	for (var id=0; id<betlive.calendar.num_tabs; id++) {
		// every tab has two tables - one for all events and one for stream events
		var tableItems = document.getElementById("tab".concat(id)).getElementsByTagName('table');
		var pItems = document.getElementById("tab".concat(id)).getElementsByTagName('p');
		//show all
		if (!streamOnly) {
			if (tableItems[0] != null) tableItems[0].style.display = 'block';
			if (tableItems[1] != null) tableItems[1].style.display = 'none';
			if (pItems[0] != null) pItems[0].style.display = 'block';
			if (pItems[1] != null) pItems[1].style.display = 'none';
		}
		//show stream only
		else {
			if (tableItems[0] != null) tableItems[0].style.display = 'none';
			if (tableItems[1] != null) tableItems[1].style.display = 'block';
			if (pItems[0] != null) pItems[0].style.display = 'none';
			if (pItems[1] != null) pItems[1].style.display = 'block';
		}
	}
}


function showPage(tab, page, streamOnly) {
	var table_idx = (streamOnly) ? 1 : 0;
	var id_sfx = (streamOnly) ? "_stream" : "_all";
	var id_pfx = (streamOnly) ? "stream_" : "all_";

	var tableItems = document.getElementById("tab".concat(tab)).getElementsByTagName('table');
	var trItems = tableItems[table_idx].getElementsByTagName('tr');

	// hide all
	for (var i=0; i<trItems.length; i++) {
		trItems[i].style.display = 'none';
	}

	// display those in the correct page
	var from = page*10;
	var to = page*10 + 10;
	for (var i=from; i<to;i++) {
		var id = "tab".concat(tab).concat("_ev").concat(i).concat(id_sfx);
		if (document.getElementById(id) == null) break;
		document.getElementById(id).style.display = '';
	}
	var spanItems = document.getElementById(id_pfx.concat('links_').concat(tab)).getElementsByTagName('span');
	// toogle style display for the current pagelink
	for (var i=0; i<spanItems.length; i++) {
		if (spanItems[i].id.indexOf('_selected') != -1) {
			if (spanItems[i].style.display != 'none') {
				spanItems[i].style.display = 'none';
			}
		}
		else {
			if (spanItems[i].style.display == 'none') {
				spanItems[i].style.display = '';
			}
		}
	}

	// toogle style display for the new pagelink
	var spanToDisplay = document.getElementById('pagelink_'.concat(tab).concat('_').concat(page).concat(id_sfx).concat('_selected'));
	var spanToDisplayHide = document.getElementById('pagelink_'.concat(tab).concat('_').concat(page).concat(id_sfx));
	spanToDisplay.style.display = '';
	spanToDisplayHide.style.display = 'none';

}


function mediaCentreToggle(name){

	var toggleOptions = new Array('video','updates');
	var displayVal = '';
	var classNameVal = '';
	toggleOptions.each(function (option) {
		if (option == name) {
			// Show the icon/content
			displayVal = "block";
			classNameVal = "off";
		} else {
			//Hide the icon/content
			displayVal = "none";
			classNameVal = "on";
		}
		if ($('media-' + option)) {
			$('media-' + option).style.display = displayVal;
		}
		if ($('icon-' + option)) {
			$('icon-' + option).className = classNameVal;
		}
	});

}


function mediaCentrePopOut(ev_id) {
	if (!betlive.mediacenter.popout.opener) {
		// Open the Pop Out media center
		var url = betlive.mediacenter.popout.url + '&ev_id=' + ev_id;
		betlive.mediacenter.popout.opener = window.open(url, betlive.mediacenter.popout.name, betlive.mediacenter.popout.win_features);

		// Hide the media center from the main window
		$('menu3').style.display = "none";
	}
}


function mediaCentrePopBack() {

	// The name which we expect the main PPW window to have.
	var main_win_name = 'ppmain';

	var 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?
	var opener_closed;
	if (!opener_window) {
		opener_closed = true;
	} else {
		opener_closed = opener_window.closed;
	}

	if (opener_closed) {
		// PPW main window already closed
	} else if (opener_name != main_win_name) {
		// The opener is using a different protocol or was not
		// opened by PPW (3rd party)
		// Close the remote media center
	} else {
		// Our opener is the PPW main window and on the same protocol.
		opener_window.parent.document.getElementById('menu3').style.display = "block";
		opener_window.parent.betlive.mediacenter.popout.opener = false;

		// close the media center window
		window.close();
	}

}


function showToggle(name){ // for initially shown elements
	var x = document.getElementById(name).style.display;
	if(x==""){
		document.getElementById(name).style.display = "none";
	}
	else{
		document.getElementById(name).style.display = "";
	}
}


function marketToggle(name){
	showToggle(name);
	if(document.getElementById(name+'-button').className == 'collapse'){
		document.getElementById(name+'-button').className = 'expand';
	}
	else{
		document.getElementById(name+'-button').className = 'collapse';
	}
}

function refreshMyBets(url) {
	
	new Ajax.Updater('myBets', url, { method: 'get', evalScripts: true });
	
}


//FINANCIALS CODE BELOW


function lb_inject_new_financials_object() {
	// inject the new javascript
	new Ajax.Updater('financials_js', betlive.event.financial_js_url, { method: 'get', evalScripts: true });
}


function lb_set_financials_countdown_to_refresh() {
	setInterval("lb_financials_countdown_to_refresh()", 1000);
	betlive.event.financial_mkt_load_countdown_started = 1;
}
	
// Display and countdown until financialmarket reload
function lb_financials_countdown_to_refresh() {
	
	if (betlive.event.financial_mkt_load_countdown <= 0) {
		// stop the javascript polle
		window.clearInterval(betlive.event.currently_live_poller);
		lb_inject_new_currently_live();
		return;
	}
	
	betlive.event.financial_mkt_load_countdown = betlive.event.financial_mkt_load_countdown - 1;
}



//TIMER CODE BELOW

var _countDowncontainerId="";
var _countDowncontainer="";
var _currentSeconds=0;
var _warningMessage="";
var _warningMessageVisible = 0;
var _pageRefresh = 0;

function ActivateCountDown(strContainerID, initialValue) {
	_countDowncontainerId = strContainerID;

	SetCountdownText(initialValue);
	window.setTimeout("CountDownTick()", 1000);
}

function CountDownTick() {

	if ((_pageRefresh) && (_currentSeconds - 1 == 0)) {
		// stop the javascript poller
		window.clearInterval(betlive.event.currently_live_poller);
		lb_inject_new_currently_live();
		return
	}

	SetCountdownText(_currentSeconds-1);
	window.setTimeout("CountDownTick()", 1000);
}



function SetCountdownText(seconds) {
	//store:
	
	_countDowncontainer = document.getElementById(_countDowncontainerId);
	
	if (seconds < 0) {
		seconds = 0;
	}
	
	_currentSeconds = seconds;

	//get minutes:
	var minutes=parseInt(seconds/60);

	//shrink:
	seconds = (seconds%60);

	//get hours:
	var hours=parseInt(minutes/60);

	//shrink:
	minutes = (minutes%60);
	
	if (_currentSeconds <= betlive.event.warn_threshold) {
		strText = _warningMessage;
		
		// blink the warning message
		if (_warningMessageVisible) {
			_countDowncontainer.style.visibility = 'hidden';
			_warningMessageVisible = 0;
		} else {
			_countDowncontainer.style.visibility = 'visible';
			_warningMessageVisible = 1;
		}
		
	} else {
		
		// make sure the text is visible
		_countDowncontainer.style.visibility = 'visible';
		
		strText = AddZero(hours) + ":" + AddZero(minutes) + ":" + AddZero(seconds);
	}
	
	//apply:
	_countDowncontainer.innerHTML = strText;
}

function AddZero(num) {
	return ((num >= 0)&&(num < 10))?"0"+num:num+"";
}
