/*
 * $Id: prem.js,v 1.30.20.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
 */

//
// Display or hide Favourite picks dorpdown/button
// check_favourites is S6 specific, this is generic
// (although currently only used by P10).
//
function check_favourites_prem() {

	// Get the game index from the current saxgame_id
	var game_idx = get_game_index(document.getElementById('FPBG_GAME_CURRENT').value.split('_')[2]);

    // Get the type of favourite picked
    var fav_picks = document.getElementById('fav_sel');

    // Reset the count of picks for this favourite type
    fav_picks.options.length = 0

    // Initialise the array in the style of the template
    fav_picks.options[0] = new Option("Guest Picks", "", true, false);

    var count = 1;

	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 each type
    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('favourites').style.visibility = 'visible';
    } else {
        document.getElementById('favourites').style.visibility = 'hidden';
    }

}


function selectFavourites(fav_type) {

	if (fav_type == "-") return;

	var game_idx = get_game_index(document.getElementById('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(game_idx,b.row,b.col);
		}
	}
	for (var i in eval('favourites_'+fav_type.toLowerCase())[game_idx]) {
		var b = eval('favourites_'+fav_type.toLowerCase())[game_idx][i];
		buttonClickWrapper(game_idx,b.row,b.col);
	}
}


// when a button is clicked the x,y co-ords are passed
function buttonClick(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 = '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(game_idx);
	
}

// checks to make sure if the form is in a completed state
function checkCompleted(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("betNow1").style.display="block";
		document.getElementById("betNow2").style.display="none";
	}
	else
	{
		document.getElementById("betNow1").style.display="none";
		document.getElementById("betNow2").style.display="block";
	}
	
	permutationFormula(game_idx);
}

// works out the current cost according to a permutation formula
function permutationFormula(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];

	/* If the stake has a decimal point then two digits must follow it.
	   If not ::ob_xgbet::_check_arg (sportech_shared) will reject it. */
	if(!checkCCYformat(permValue)) permValue = permValue.toFixed(2);

	document.getElementById('price_display').innerHTML = formatCurrency(permValue,false);
	document.getElementById('price').value = permValue;
}

// Performs the same check as the  ::ob_xgbet::_check_arg proc
function checkCCYformat(permValue){
	var ccy_format = /^[0-9]+(\.[0-9][0-9])?$/;
	return ccy_format.test(permValue); //returns true or false depending on 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(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 = '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(game_idx);
}

function doDropDown(theDD) {
	
	// Switch off the display of the previously selected game
	document.getElementById(document.getElementById('FPBG_GAME_CURRENT').value).style.display = 'none';

	// Switch on the display of the newly selected game
	document.getElementById(theDD.options[theDD.selectedIndex].value).style.display = 'block';
	document.getElementById('FPBG_GAME_CURRENT').value = theDD.options[theDD.selectedIndex].value;
	checkCompleted(theDD.selectedIndex);

	// 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('FPBG_GAME_CURRENT_closedate').value =
		document.getElementById('FPBG_GAME_' + theDD.selectedIndex + '_closedate').value;

	document.getElementById('FPBG_GAME_SHOW_closedate').innerHTML =
		document.getElementById('FPBG_GAME_' + theDD.selectedIndex + '_closedate').value;

	document.getElementById('FPBG_GAME_CURRENT_fund_estimate').value =
		document.getElementById('FPBG_GAME_' + theDD.selectedIndex + '_fund_estimate').value;

	document.getElementById('FPBG_GAME_CURRENT_jackpot_estimate').value =
		_tmp = document.getElementById('FPBG_GAME_' + theDD.selectedIndex + '_jackpot_estimate').value;

	var _tmp_desc = document.getElementById('FPBG_GAME_' + theDD.selectedIndex + '_description').value;
	document.getElementById('FPBG_GAME_CURRENT_description').value = _tmp_desc;
	document.getElementById('FPBG_GAME_description').innerHTML = _tmp_desc;

	// Update pundit information for this game
	var game_idx = get_game_index(document.getElementById('FPBG_GAME_CURRENT').value.split('_')[2]);
	
	if (document.getElementById('pundit_comment')) {	
		document.getElementById('pundit_comment').innerHTML     = favourites_info[game_idx]['pundit_comment'];
		document.getElementById('pundit_photo').src             = favourites_info['gif_url'] + '/' + favourites_info[game_idx]['pundit_photo'];
		document.getElementById('pundit_main_text').innerHTML   = favourites_info[game_idx]['pundit_main_text'];
		document.getElementById('pundit_profile_link').href     = favourites_info[game_idx]['pundit_profile_link'];
		document.getElementById('pundit_all_preview_link').href = favourites_info[game_idx]['pundit_all_preview_link'];
	}

	// Update celebrity information for this game
    // check needed as midweek games have no celeb picks
	if (document.getElementById('celeb_comment')) {
		document.getElementById('celeb_comment').innerHTML     = favourites_info[game_idx]['celeb_comment'];
		document.getElementById('celeb_photo').src             = favourites_info['gif_url'] + '/' + favourites_info[game_idx]['celeb_photo'];
		document.getElementById('celeb_main_text').innerHTML   = favourites_info[game_idx]['celeb_main_text'];
		document.getElementById('celeb_profile_link').href     = favourites_info[game_idx]['celeb_profile_link'];
		document.getElementById('celeb_all_preview_link').href = favourites_info[game_idx]['celeb_all_preview_link'];
	}

	if (document.getElementById('extra_comment')) {
		document.getElementById('extra_comment').innerHTML     = favourites_info[game_idx]['extra_comment'];
		document.getElementById('extra_photo').src             = favourites_info['gif_url'] + '/' + favourites_info[game_idx]['extra_photo'];
		document.getElementById('extra_main_text').innerHTML   = favourites_info[game_idx]['extra_main_text'];
		document.getElementById('extra_profile_link').href     = favourites_info[game_idx]['extra_profile_link'];
		document.getElementById('extra_all_preview_link').href = favourites_info[game_idx]['extra_all_preview_link'];
	}
	// Update the prize structure explaination with appropriate jackpot value
	//var _jackpot = jackpots[game_idx];
	//document.getElementById('prize_structure').innerHTML = prize_structure_txt.replace(/__JACKPOT__/,_jackpot);

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

/*
Due to the nature of the P10 comp using different classes and ids, this is a
small helper proc that updates the pundits div to show the correct competition.
*/
function doUpdateCompetitionPunditsStandalone(comp_index) {

	//Get the number of comps in the drop down
	var max_index = parseInt(document.getElementById('max_comp').value);

	for (j = 0; j < max_index; j++)
	{
		//To avoid overlap, hide existing information for all the divs
		document.getElementById('pundit_'+ j).style.display = 'none';
	}

	// Now display the correct information
	document.getElementById('pundit_' + comp_index).style.display = 'block';

}


function doUpdateCompetition(comp_index) {
	
	// Switch off the display of the previously selected game
	document.getElementById(document.getElementById('FPBG_GAME_CURRENT').value).style.display = 'none';
	var prev_comp_index = document.getElementById('sel_comp').value;
	document.getElementById('comp_div_' + prev_comp_index).className = '';

	// 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(fpbg_game).style.display = 'block';
	document.getElementById('FPBG_GAME_CURRENT').value = fpbg_game;
	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(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('FPBG_GAME_CURRENT_closedate').value =
		document.getElementById('FPBG_GAME_' + comp_index + '_closedate').value;

	document.getElementById('FPBG_GAME_SHOW_closedate').innerHTML =
		document.getElementById('FPBG_GAME_' + comp_index + '_closedate').value;

	document.getElementById('FPBG_GAME_CURRENT_fund_estimate').value =
		document.getElementById('FPBG_GAME_' + comp_index + '_fund_estimate').value;

	document.getElementById('FPBG_GAME_CURRENT_jackpot_estimate').value =
		_tmp = document.getElementById('FPBG_GAME_' + comp_index + '_jackpot_estimate').value;

	var _tmp_desc = document.getElementById('FPBG_GAME_' + comp_index + '_description').value;
	document.getElementById('FPBG_GAME_CURRENT_description').value = _tmp_desc;
	document.getElementById('FPBG_GAME_description').innerHTML = _tmp_desc;

	var siteviewid = document.getElementById('FPBG_GAME_siteveiwid').value;
	var game_type = document.getElementById('game_type').value;
 	showStatsAndData(comp_index,0,siteviewid,game_type);
}

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(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('BALL_' + game_idx + '_' + i + '_' + j).value;
            }
        }
        if(_tmpSelections.length > 0) _tmpSelsGrps[_tmpSelsGrps.length] = _tmpSelections.join(_selsDelimiter);
    }

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

    // Adding the stake
    	if(isMatrix == "Y"){
    		_tmpBet[1] = cost[game_idx];
	} else {
    		_tmpBet[1] = document.getElementById('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;

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

		buttonClickWrapper(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;
	for(var i = 0 ; i < _selns.length ; i++) {
		_tmp = parseInt(_selns[i]);
		if(_tmp < 1) continue;
		_tmp_name = 'BALL_0_' + parseInt((_tmp - 1) / 3) + '_' + ((_tmp - 1) % 3);
		if(!document.getElementById(_tmp_name)) continue;
		if(document.getElementById(_tmp_name).value != _tmp) continue;
		buttonClick(_game_idx, parseInt((_tmp - 1) / 3), ((_tmp - 1) % 3));
	}
}

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);
}

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");

	// Storing the current competition displayed
	_competitions[1] = document.getElementById('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('BALL_' + g + '_' + i + '_' + j).value;
			}
        }
        _tmpBet[3] = _tmpSelections.join(_selsDelimiter);

        _competitions[_competitions.length] = _tmpBet.join(_betDelimiter);
	}

	// 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()
{
	var cost = 0;
	document.getElementById('price_display').innerHTML = formatCurrency(cost,false);
	document.getElementById('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";
			}

		}
	}
}

