/*
 * $Id: prems6.js,v 1.14.6.1 2010-06-09 13:35:20 alongwil Exp $
 * Copyright (c) 2008 Orbis Technology Ltd. All rights reserved.
 *
 * This javascript file is sourced from the html/gameon/football/js/prem.html file and should not
 * be sourced from anywhere else unless the required constants and arrays are provided
 */
 
function selectFavourites(prefix,fav_type) {

	if (fav_type == "-") return;

	var game_idx = get_game_index(document.getElementById(prefix +'_FPBG_GAME_CURRENT').value.split('_')[2]);
	
	for (i=0; i < all[game_idx].length; i++){
		var b = all[game_idx][i];
		if (array[game_idx][b.row][b.col] == 1) {
			buttonClickWrapper(prefix,game_idx,b.row,b.col);
		}
	}

	if (fav_type == "") return;

	for (var i in eval('favourites_'+fav_type.toLowerCase())[game_idx]) {
		var b = eval('favourites_'+fav_type.toLowerCase())[game_idx][i];
		buttonClickWrapper(prefix,game_idx,b.row,b.col);
	}
}


// when a button is clicked the x,y co-ords are passed
function buttonClickMutiSlip(prefix,game_idx,x,y)
{
	// gets the current value (selected/not selected)
	var value = array[game_idx][x][y];
	
	// gets the two combined as a string
	var data = prefix+'_DATA_' + game_idx + '_' + x + '_' + y;
	
	// checks if the value is selected
	if (value == 1)
	{
		// deselects the value
		document.getElementById(data).setAttribute("src",getParameter("GIF_URL") + "/Play/false.png");
		value = 0;
	} 
	// checks if the value is not selected
	else if ( value == 0)
	{
		// selects the value
		document.getElementById(data).setAttribute("src",getParameter("GIF_URL") + "/Play/true.png");
		value = 1;
	}
	
	// writes new value into the array
	array[game_idx][x][y] = value;

	// Check for max perms reached...
	if (!checkMaxPerms(game_idx)) 
	{
		// roll back changes
		document.getElementById(data).setAttribute("src",getParameter("GIF_URL") + "/Play/false.png");
		array[game_idx][x][y] = 0;
	}

	if (typeof(coupon) == "undefined")
		checkCompleted(prefix,game_idx);	
}


// when a button is clicked the x,y co-ords are passed
function RefreshMutiSlip(prefix,game_idx)
{
	for (i = 0; i < rows; i++)
	{	
		for (j = 0; j < cols; j++)
		{
			// gets the current value (selected/not selected)
			var value = array[game_idx][i][j];
			
			// gets the two combined as a string
			var data = prefix+'_DATA_' + game_idx + '_' + i + '_' + j;

			// checks if the value is not selected
			if (value == 0)
			{
				// deselects the value
				document.getElementById(data).setAttribute("src",getParameter("GIF_URL") + "/Play/false.png");
			} 
			// checks if the value is selected
			else if ( value == 1)
			{
				// selects the value
				document.getElementById(data).setAttribute("src",getParameter("GIF_URL") + "/Play/true.png");
			}	
		}
	}

	if (typeof(coupon) == "undefined")
		checkCompleted(prefix,game_idx);	
}


// checks to make sure if the form is in a completed state
function checkCompleted(prefix,game_idx)
{	
	// variable to decide if the selections are in a completed state
	var completed = 1;

	// checks each value in the array
	for (i = 0; i < array[game_idx].length; i++)
	{
		// at least one value per row must be selected
		var isRowSelected = 0;
		
		for (j = 0; j < array[game_idx][i].length; j++)
		{
			// if the a col in row is selected
			if(array[game_idx][i][j] == 1)
			{
				isRowSelected = 1;
				break;
			}
		}
		
		// if no columns are selected in that row
		if (isRowSelected == 0) 
		{
			completed = 0;
			break;
		}		
	}
	
	// shows/hides the submit button
	if (completed == 1)
	{
		document.getElementById(prefix+"_betNow1").style.display="block";
		document.getElementById(prefix+"_betNow2").style.display="none";
	}
	else
	{
		document.getElementById(prefix+"_betNow1").style.display="none";
		document.getElementById(prefix+"_betNow2").style.display="block";
	}
	
	permutationFormula(prefix,game_idx);
}


// works out the current cost according to a permutation formula
function permutationFormula(prefix,game_idx)
{
	var permArray = new Array();

	// goes through array and works out how many are selected
	for (i = 0; i < array[game_idx].length; i++)
	{
		var numSelected = 0
		for (j = 0; j < array[game_idx][i].length; j++)
		{			
			if (array[game_idx][i][j] == 1)
			{
				numSelected++;
			}
			
			permArray[i] = numSelected;
		}
	}
	
	var permValue = 1;
	
	for (i = 0; i < array[game_idx].length; i++)
	{
		permValue = permValue * permArray[i];
	}
	
	permValue = permValue * cost[game_idx];
	
	document.getElementById(prefix+'_price_display').innerHTML = formatCurrency(permValue,false);
	document.getElementById(prefix+'_price').value = permValue;
}


// if the submit button is pressed
function ok(game_idx)
{
	// gets current id from the drop down
	var compdropdown = document.getElementById('dropdown');

	var id = compdropdown.options[compdropdown.selectedIndex].value;
	
	// the url of the submit page
	var url = "submitpage.html?id=" + id + "&";
	var seperator = "";
	
	// gets selected from array
	for (i = 0; i < array[game_idx].length; i++)
	{
		var current = seperator + "Selection" + i + "=";
		var comma = "";
	
		for (j = 0; j < array[game_idx][i].length; j++)
		{
			current += array[game_idx][i][j];
		}
		
		url += current;
		seperator = "&";
	}
	
	// redirects to that page
	location.href = url;
}


function clear(prefix,game_idx)
{
	// sets all values of the array to 0
	for (i = 0; i < array[game_idx].length; i++)
	{
		for (j = 0; j < array[game_idx][i].length; j++)
		{
			var data = prefix+'_DATA_' + game_idx + '_' + i + '_' + j;
			// resets image to unchecked
			document.getElementById(data).setAttribute("src",getParameter("GIF_URL") + "/Play/false.png");
			array[game_idx][i][j] = 0;
		}
	}
	checkCompleted(prefix,game_idx);
}


/*

Update competitions wrapper for multi betting slips.

*/
function doUpdateCompetitionWrapper(comp_index) {

	// If no comp_index is passed in, default to the first index
	// of the dropdown.
	if (comp_index == "") {
		comp_index = 0;
	}

	// List of all the ids 
	var Competition_list = document.getElementById('dropdown');

	// Array containing a list of the competitions not being show
	var Remaining_Competitions = [];

	// Number of competitions
	var counter = 0

	/*
	 Find which competition that has been selected to be show in the
	 primary betting slip (Slip1).  Remove this from the list of competetions
	 and then add the remainers to the Remaining_Competitions for use when
	 deciding which other competitions to display.
	*/
	for (i = 0; i < Competition_list.options.length; i++) {

		// Remove the com_index from the array
		if (i != comp_index ) {
			Remaining_Competitions[counter] = i;
			++counter;
		}
	}

	/*
	Display the correct header for main
	*/
	// Switch off the display of the previously selected game
	var main_game = document.getElementById('SLIP1_FPBG_GAME_CURRENT').value;
	document.getElementById('SLIP1_'+ main_game).style.display = 'none';

	// Switch on the display of the newly selected game
	var fpbg_game = document.getElementById('comp_' + comp_index).value;
	document.getElementById('comp_div_' + comp_index).className = 'coupon_selected_competition';
	document.getElementById('SLIP1_'+fpbg_game).style.display = 'block';
	document.getElementById('SLIP1_FPBG_GAME_CURRENT').value = fpbg_game;

	//Run the updating of the competition details
	doUpdateCompetition("SLIP1",comp_index);

	//now refresh the various slips
	var main_game_idx = get_game_index(document.getElementById('SLIP1_FPBG_GAME_CURRENT').value.split('_')[2]);
	RefreshMutiSlip("SLIP1",main_game_idx);
	insertFundAndJackpot('SLIP1_FPBG_GAME');

	//disable/enable favourites
	check_favourites("SLIP1",main_game_idx,"P06WM");


	/*
	Setup if the extra comps (If available)
	*/
	//check to see if we have more than one comp
	if (Remaining_Competitions.length > 0) {

		// More than 1 comp
		if ( typeof(Remaining_Competitions[0]) != "undefined" ) {
	
			// Switch off the display of the previously selected game
			var main_game = document.getElementById('SLIP2_FPBG_GAME_CURRENT').value;
			document.getElementById('SLIP2_'+ main_game).style.display = 'none';
		
			// Switch on the display of the newly selected game
			var fpbg_game = document.getElementById('comp_' + Remaining_Competitions[0]).value;
			document.getElementById('comp_div_' + comp_index).className = 'coupon_selected_competition';
			document.getElementById('SLIP2_'+fpbg_game).style.display = 'block';
			document.getElementById('SLIP2_FPBG_GAME_CURRENT').value = fpbg_game;

			doUpdateCompetition("SLIP2",Remaining_Competitions[0]);
		
			//now refresh the various slips
			var main_game_idx = get_game_index(document.getElementById('SLIP2_FPBG_GAME_CURRENT').value.split('_')[2]);
			RefreshMutiSlip("SLIP2",main_game_idx);
			insertFundAndJackpot('SLIP2_FPBG_GAME');

			//disable/enable favourites
			check_favourites("SLIP2",main_game_idx,"P06WM");
		
		}

		//Check if we have 3 full competitions
		if ( typeof(Remaining_Competitions[1]) != "undefined" ) {
	
			// Switch off the display of the previously selected game
			var main_game = document.getElementById('SLIP3_FPBG_GAME_CURRENT').value;
			document.getElementById('SLIP3_'+ main_game).style.display = 'none';
		
			// Switch on the display of the newly selected game
			var fpbg_game = document.getElementById('comp_' + Remaining_Competitions[1]).value;
			document.getElementById('comp_div_' + comp_index).className = 'coupon_selected_competition';
			document.getElementById('SLIP3_'+fpbg_game).style.display = 'block';
			document.getElementById('SLIP3_FPBG_GAME_CURRENT').value = fpbg_game;
		
			doUpdateCompetition("SLIP3",Remaining_Competitions[1]);
		
			//now refresh the various slips
			var main_game_idx = get_game_index(document.getElementById('SLIP3_FPBG_GAME_CURRENT').value.split('_')[2]);
			RefreshMutiSlip("SLIP3",main_game_idx);
			insertFundAndJackpot('SLIP3_FPBG_GAME');

			//disable/enable favourites
			check_favourites("SLIP3",main_game_idx,"P06WM");
	
		} else {
			document.getElementById('ThirdComp').style.display = 'none';
		}
	}
}


//
// Display or hide Favourite picks dorpdown/button
//
function check_favourites(prefix,game_idx,game_type) {

	// Get the select statement
	var fav_picks = document.getElementById(prefix + '_guestPicks');

	// Reset the array
	fav_picks.options.length=0

	// Add the picks Header
	fav_picks.options[0]=new Option("Guest Picks", "", true, false);

	var count = 1;

	//Super 6 does not contain Extra or Celeb picks
	if (game_type == "P06WM" ) {
		var avail_favs = ["p"];
		var avail_favs_names = ["Pundits"]
	} else {
		var avail_favs = ["p","e","c"];
		var avail_favs_names = ["Pundits","Extra","Celeb Picks"]
	}

	//Check to see if the favourites array has any data items
	for ( var i in avail_favs ) {
		if ((eval('favourites_'+avail_favs[i].toLowerCase())[game_idx].length) > 0) {
			fav_picks.options[count]=new Option(avail_favs_names[i], avail_favs[i], true, false);
			count++
		}
	}
	
	// Are there any items worth showing?
	if(count < 2) {
		fav_picks.disabled = true;
	} else {
		fav_picks.disabled = false;
	}

	// Now check the bookies picks
	// If picks are availible then display
	if ((eval('favourites_b')[game_idx].length) > 0) {
		document.getElementById(prefix + '_favourites').style.display = 'block';
	} else {
		document.getElementById(prefix + '_favourites').style.display = 'none';
	}
}


function doUpdateCompetition(prefix,comp_index) {
	
	document.getElementById('sel_comp').value = comp_index;
	document.getElementById('dropdown').selectedIndex = comp_index;
	//document.getElementById('pundit_' + prev_comp_index).style.display = 'none';
	//document.getElementById('pundit_' + comp_index).style.display = 'block';
	checkCompleted(prefix,comp_index);

	// Modifies the current close date, fund estimate and jackpot estimate to match the newly selected game
	// in order to display the correct countdown timer and estimates

	document.getElementById(prefix +'_FPBG_GAME_CURRENT_closedate').value =
		document.getElementById(prefix +'_FPBG_GAME_' + comp_index + '_closedate').value;

	document.getElementById(prefix +'_FPBG_GAME_SHOW_closedate').innerHTML =
		document.getElementById(prefix +'_FPBG_GAME_' + comp_index + '_closedate').value;

	document.getElementById(prefix +'_FPBG_GAME_CURRENT_fund_estimate').value =
		document.getElementById(prefix +'_FPBG_GAME_' + comp_index + '_fund_estimate').value;

	document.getElementById(prefix +'_FPBG_GAME_CURRENT_jackpot_estimate').value =
		_tmp = document.getElementById(prefix +'_FPBG_GAME_' + comp_index + '_jackpot_estimate').value;

	var _tmp_desc = document.getElementById(prefix +'_FPBG_GAME_' + comp_index + '_description').value;
	document.getElementById(prefix +'_FPBG_GAME_CURRENT_description').value = _tmp_desc;
	document.getElementById(prefix +'_FPBG_GAME_description').innerHTML = _tmp_desc;

	//Update slip description header
	document.getElementById(prefix +'_FPBG_GAME_HEADER_description').innerHTML = _tmp_desc;

	var siteviewid = document.getElementById('FPBG_GAME_siteviewid').value;
	var game_type = document.getElementById('game_type').value;
}

function goNextCoupon() {
	var cur_index = parseInt(document.getElementById('sel_comp').value);
	var min_index = parseInt(document.getElementById('min_comp').value);
	var max_index = parseInt(document.getElementById('max_comp').value);

	var new_index = cur_index + 1;
	if (new_index >= max_index) {
		new_index = min_index;
	}
	doUpdateCompetition(new_index);
}

function goPrevCoupon() {
	var cur_index = parseInt(document.getElementById('sel_comp').value);
	var min_index = parseInt(document.getElementById('min_comp').value);
	var max_index = parseInt(document.getElementById('max_comp').value);

	var new_index = cur_index - 1;
	if (new_index < min_index) {
		new_index = max_index - 1;
	}
	doUpdateCompetition(new_index);
}

function place_poolbetting_bet(prefix, game_idx, isMatrix) {

    var _tmpSelections = new Array();
    var _tmpSelsGrps = new Array();
    var _tmpBet = new Array();

	if(isMatrix == "Y"){
    		var _selsDelimiter = 'd';
	} else {
    		var _selsDelimiter = 'c';
	}
    var _selsGrpsDelimiter = 'c';
    var _betDelimiter = '|';

    // A group of selections contains all the selections for a given row
    // Building the bet string

    var i, j;

    for (i = 0; i < array[game_idx].length; i++) {
        _tmpSelections.length = 0;
        for (j = 0; j < array[game_idx][i].length; j++) {
            if(array[game_idx][i][j]) {
                _tmpSelections[_tmpSelections.length] = document.getElementById(prefix+'_BALL_' + game_idx + '_' + i + '_' + j).value;
            }
        }
        if(_tmpSelections.length > 0) _tmpSelsGrps[_tmpSelsGrps.length] = _tmpSelections.join(_selsDelimiter);
    }

    // Adding the game_id
    _tmpBet[0] = document.getElementById(prefix+'_FPBG_GAME_CURRENT').value.split('_')[2];

    // Adding the stake
    	if(isMatrix == "Y"){
    		_tmpBet[1] = cost[game_idx];
	} else {
    		_tmpBet[1] = document.getElementById(prefix+'_price').value;
	}

    // Adding the number of subscriptions which is alway one for the current
    // pool betting games which are Premier10 and Super15
    _tmpBet[2] = 1;

    // Adding the Openbet Plan Id here. It is always empty since no current
    // pool betting games like Premier10 and Super15 supports plan
    _tmpBet[3] = "";

    // Adding the selections
    _tmpBet[4] = _tmpSelsGrps.join(_selsGrpsDelimiter);

	// update the selectiosn array so that if we are not
	// logged in they will be maintained after login.
	make_selections(game_idx, isMatrix);

    // Placing the bet using the generic call defined in bet.html
    place_bet('Football', _tmpBet.join(_betDelimiter));
}

// update the selectiosn array so that if we are not
// logged in they will be maintained after login.
function make_selections(game_idx, isMatrix) {

	var selections = "";
	var ball       = 1;

	for (var i = 0; i < array[game_idx].length; i++) {
		for (var j = 0; j < 3; j++) {
			if (array[game_idx][i][j] == 1) selections = selections + ball + ",";
			ball++;
		}
	}
	
	// Update the selns array if it exists
	if (document.forms['login'].elements['selns'] != null) {
		// remove the trailing comma
		document.forms['login'].elements['selns'].value = selections.substring(0,selections.length - 1);
	}
}

function preselect(selections) {

	if(!selections) return;
	if(selections == "") return;
	
	var _selns = selections.split(',');
	var _tmp;
	var _tmp_name;

	var slips = ["SLIP1","SLIP2","SLIP3"];
	for ( var i in slips ) {
		var prefix = slips[i];

		for(var i = 0 ; i < _selns.length ; i++) {
			_tmp = parseInt(_selns[i]);
			if(_tmp < 1) continue;
			_tmp_name = prefix + '_BALL_0_' + parseInt((_tmp - 1) / 3) + '_' + ((_tmp - 1) % 3);
			if(!document.getElementById(_tmp_name)) continue;
			if(document.getElementById(_tmp_name).value != _tmp) continue;
	
			buttonClickWrapper(prefix,0, parseInt((_tmp - 1) / 3), ((_tmp - 1) % 3));
		}
	}
}

function load_game(game_id, selections) {
	
	if(!selections) return;
	if(selections == "") return;
	var _game_idx = get_game_index(game_id);
	if(_game_idx == -1) return;

	var _selns = selections.split('c');
	var _tmp;
	var _tmp_name;

	var slips = ["SLIP1","SLIP2","SLIP3"];
	for ( var i in slips ) {
		var prefix = slips[i];

		for(var i = 0 ; i < _selns.length ; i++) {
			_tmp = parseInt(_selns[i]);
			if(_tmp < 1) continue;
			_tmp_name = prefix + '_BALL_0_' + parseInt((_tmp - 1) / 3) + '_' + ((_tmp - 1) % 3);
			if(!document.getElementById(_tmp_name)) continue;
			if(document.getElementById(_tmp_name).value != _tmp) continue;
			buttonClickMutiSlip(prefix,_game_idx, parseInt((_tmp - 1) / 3), ((_tmp - 1) % 3));
		}
	}
	var dummy_set = 0;
}

function get_game_index(game_id) {
	// from the id, determine the index
	var compDD_opt = document.getElementById('dropdown').options;
	var _game_idx;
	for(_game_idx = 0; _game_idx < compDD_opt.length; _game_idx++) {
		if(compDD_opt[_game_idx].value.split('_')[2] == game_id) break;
	}
	return (_game_idx == compDD_opt.length ? -1 : _game_idx);
}

function display_game(game_idx) {
	var _compDD = document.getElementById('dropdown');
	_compDD.selectedIndex = game_idx;
	//doDropDown(_compDD);

	var comp_index = get_game_index(document.getElementById('SLIP1_FPBG_GAME_CURRENT').value.split('_')[2]);
	doUpdateCompetitionWrapper(comp_index);
}

function store_poolbetting_in_cookie() {

	var _tmpSelections = new Array();
	var _tmpBet = new Array();
	var _competitions = new Array();
	var _selsDelimiter = 'c';
	var _betDelimiter = '|';
	var _competitionDelimiter = "X";

	var i, j, g;
	var _ta;
	var _saxgame_id;

	_competitions.length = 0;

	// Storing the game sort
	_competitions[0] = getParameter("football_game");

	//var slips = ["SLIP1","SLIP2","SLIP3"];
	
	var slips = ["SLIP1"]

	var comp_count = 1;

	for ( var i in slips ) {

		var prefix = slips[i];

		// Storing the current competition displayed
		_competitions[comp_count] = document.getElementById(prefix + '_FPBG_GAME_CURRENT').value.split('_')[2];

		// Storing each competition
		for (g = 0; g < array.length; g++) {
	
			_tmpBet.length = 0;
	
			// Adding the openbet saxgame_id
			_saxgame_id = document.getElementById('dropdown').options[g].value.split('_')[2];
			_tmpBet[0] = _saxgame_id;
	
			// Storing the plan_id
			_tmpBet[1] = '';
	
			// Storing the number of subscriptions
			_tmpBet[2] = '';
	
			// Storing the current/temporary selections
			_ta = array[g];
			_tmpSelections.length = 0;
			for (i = 0; i < _ta.length; i++) {
				for (j = 0; j < _ta[i].length; j++) {
					if(_ta[i][j]) _tmpSelections[_tmpSelections.length] = document.getElementById(prefix + '_BALL_' + g + '_' + i + '_' + j).value;
				}
			}
			_tmpBet[3] = _tmpSelections.join(_selsDelimiter);
	
			_competitions[_competitions.length] = _tmpBet.join(_betDelimiter);
		}		
		comp_count++;
	}

	// Saving the game in a cookie
	clear_save_cookie();
	save_gameplay(_competitions.join(_competitionDelimiter));
}


// checks the current cost depending on number of permutations seleted
function checkMaxPerms(game_idx)
{
	var permArray = new Array();

	// searches array for number selected
	for (i = 0; i < array[game_idx].length; i++)
	{
		numSelected = 0;
		for (j = 0; j < array[game_idx][i].length; j++)
		{
			if (array[game_idx][i][j] == 1)
			{
				// counts number selected
				numSelected++;
			}
			permArray[i] = numSelected;
		}
	}
	var permValue = 1;
	
	// multplies up perms
	for (i = 0; i < array[game_idx].length; i++)
	{
		permValue = permValue * permArray[i];
	}

	if (permValue > MAXPERMS)
	{
		alert('Your selections would result in more than ' + MAXPERMS + ' lines which is not allowed');
		return false;
	}
	return true;
}

function resetPrice(slipName)
{
	var cost = 0;
	document.getElementById(slipName+'_price_display').innerHTML = formatCurrency(cost,false);
	document.getElementById(slipName+'_price').value = cost;
}

function showStatsAndData(game_idx, match_idx, id, sort)
{
	var pundit_id = "";
	var punditsDropdown = document.getElementById('punditsDropdown_' + game_idx);
	if (punditsDropdown != null) {
		var punditsDropdownValue = punditsDropdown.value;
		if (punditsDropdownValue == "P") {
			if (favourites_info[game_idx]['pundit_id'] != null) {
				pundit_id = favourites_info[game_idx]['pundit_id'];
			}
		} else if (punditsDropdownValue == "C") {
			if (favourites_info[game_idx]['celeb_id'] != null) {
				pundit_id = favourites_info[game_idx]['celeb_id'];
			}
		}  else {
			if (favourites_info[game_idx]['extra_id'] != null) {
				pundit_id = favourites_info[game_idx]['extra_id'];
			}
		}
	}
	
	if (document.getElementById('MATCH_INFO_' + game_idx + '_' + match_idx).value) {
		var url = document.getElementById('MATCH_INFO_' + game_idx + '_' + match_idx).value;
		if (url != "") {
			url = url + "&channel="+id+"&sort="+sort+"&pundit="+pundit_id;
 		}
	} else {
		var url = "http://community.footballpools.com/head2head.html";
	}

	// backwards compatibility
	if (document.getElementById('statsAndDataFrame')) {
		document.getElementById('statsAndDataFrame').src = url;
	} else {
		document.getElementById('statsAndDataFrame_' + game_idx).src = url;
	}

	if (id=="8") {
		// Display football icon
		for (i = 0; i < array[game_idx].length; i++)
		{
			if (i == match_idx)
			{
				document.getElementById('BALL_IMAGE_' + game_idx + '_' + i).style.visibility="visible";
			}
			else 
			{
				document.getElementById('BALL_IMAGE_' + game_idx + '_' + i).style.visibility="hidden";
			}
		}
	}
}


/*
The function overrides the version in util.js and is specific to the p06WM game
*/
function updateCounterTime(basename,daysLeft,hoursLeft,minsLeft,secsLeft) {

		if (document.getElementById(basename + "_countdown"))
			document.getElementById(basename + "_countdown").innerHTML = daysLeft + " days " + hoursLeft + " hrs " + minsLeft + " mins " + secsLeft + " secs";
}

