var placeBetTimer = 0;
var originalButtonText = '';
var busyPlacingBet = false;

function addToBettingSlip(oddsId, betCalc) {
	if (busyPlacingBet)
	{
		return;
	}
	
	if (typeof betCalc == 'undefined')
	{
		betCalc = '';
	}
	
	$.ajax({
		type: 'post',
		url: $("#ajaxProvideraddToBettingSlipUrl").val(),
		dataType: 'json',
		data: 'oddsId=' + oddsId + '&betCalc=' + betCalc,
		
		complete: function() {
            if ( $('#stakeTable').is(':hidden') ){
                var showMulti = 1;
            } else {
                var showMulti = 0;
            }
            getBettingSlip();
            if (showMulti){
                $('#multiTable').show();
                $('#stakeTable').hide();
            } else {
                $('#multiTable').hide();
                $('#stakeTable').show();
            }
		},
		
		error: function(data){
			alert(data);
		},
		

		success: function(data) {
			
			var json = eval(data);
			$('#ajaxMessage').attr("innerHTML",'<p class="message-'+json.type+'">'+json.message+'</p>');
			$("#ajaxMessage").fadeIn("slow");
			$("#ajaxMessage").fadeOut(5000);
			
			
		}
	});
}

/*
 * restore bet button to original state
 */ 
function revertBetButton() {
	if (originalButtonText != '') {
		$('#place_bet').text(originalButtonText);
	} //if
	
    $('#place_bet').attr('disabled', '');
    $('#bet_loader').hide();
    
    if (typeof placeBetTimer != 'undefined') {
    	clearInterval(placeBetTimer);
    } //if
    
    busyPlacingBet = false;
}

/*
 * temporarily disable bet button (for use during slip updates, etc.)
 */
function toggleBetButton(disable) {
	if (disable) {
		$('#place_bet').addClass('disabled');
		$('#place_bet').attr('disabled', 'disabled');
		$('#fund_bet').addClass('disabled');
		$('#fund_bet').attr('disabled', 'disabled');		
	} else {
		$('#place_bet').removeClass('disabled');
		$('#place_bet').attr('disabled', '');
		$('#fund_bet').removeClass('disabled');
		$('#fund_bet').attr('disabled', '');		
	}
}

function startWaitingBetButton() {
	if (parseInt($('#liveSpreadBet').val()) == 1 || parseInt($('#liveBet').val()) == 1) {
		originalButtonText = $('#place_bet').text();	
		var sleepAmount = parseInt($('#betButtonCountdown').val());
		
		$('#place_bet').text('Wait (' + (sleepAmount + 1) + ') ... ');
		$('#place_bet').attr('disabled', 'disabled');
		$('#bet_loader').show();
		busyPlacingBet = true;
			
		placeBetTimer = setInterval(function() { 
		   $('#place_bet').text('Wait (' + (sleepAmount--) + ') ... ');
		   if (sleepAmount == -1) {
			   revertBetButton();
		   } 
		}, 1000);
	}
}

function addWager() {
    $('#place_bet').attr('disabled', 'disabled');
    $('#fund_bet').attr('disabled', 'disabled');

    var wagerdata = '';  
	var noContinue = 0;
    var noSingleContinue = 0;
    var noMultiContinue = 0;
	var temp = Array();
	
	var userId = $('#usr_id').val();// for normal call centre

	var tempUserId = $('#cashBetUserId').val(); //if defined override user id
	if (typeof tempUserId != 'undefined'){
		userId = tempUserId;
		if(tempUserId == '0') {
			alert ('No Cash User Id Set!');
            $('#place_bet').attr('disabled', '');
            $('#fund_bet').attr('disabled', '');
			return false;
		}
	}
	wagerdata = 'userId=' + userId + '&';

    $('#stakeTable input').each(function(idx, item) {  
		if (item.id.indexOf('stake') >= 0){
			temp = item.id.split('_');
			if (item.value > 0){
				//alert ("Your stake must be higher than 1");
				//noSingleContinue = 1;
				//return false;
			//} else {
                //wagerdata += "stake[" + temp[1] + "][value]=" + item.value + "&stake[" + temp[1] + "][odds]=" + $("#odds_" + temp[1]).val() + "&";
                if ($("#eachway_" + temp[3]).is(':checked')){
                    wagerdata += "stakeType[|" + temp[1] + "][" + temp[2] + "][value]=" + item.value + "&stakeType[|" + temp[1] + "][" + temp[2] + "][count]=" + temp[3] + "&";
                } else {
                    wagerdata += "stakeType[|" + temp[1] + "][" + temp[2] + "][value]=" + item.value + "&stakeType[|" + temp[1] + "][" + temp[2] + "][count]=" + temp[3] + "&";
                }
                
            }
		}
        
    });
    
    $('#multiTable input').each(function(idx, item) {  
		if (item.id.indexOf('stake') >= 0){
			temp = item.id.split('_');
			if (item.value > 0){
				//alert ("Your stake must be higher than 1");
				//noMultiContinue = 1;
				//return false;
			//} else {
                if (temp[1].indexOf('Takeback') >= 0)
                {
                    item.value = Math.abs(item.value) * -1; //Shaun force negative value for takeback bets...
                }
                wagerdata += "stakeType[" + temp[1] + "][" + temp[2] + "][value]=" + item.value + "&stakeType[" + temp[1] + "][" + temp[2] + "][count]=" + temp[3] + "&";
            }
		}
        
    });

    if (noSingleContinue && noMultiContinue){
        noContinue = 1;
    }
	//alert(wagerdata); 
	
	if (wagerdata == ""){
		alert("You need to bet on something. Please ensure that your stake is higher than the minimum amount.");
        $('#place_bet').attr('disabled', '');
        $('#fund_bet').attr('disabled', '');
		return false;
	}
	if (noContinue){
        $('#place_bet').attr('disabled', '');
        $('#fund_bet').attr('disabled', '');
		return false;
	}	
	
	startWaitingBetButton();

    $.ajax({
		type: 'post',
		url: $("#ajaxProvideraddWagerUrl").val(),
		dataType: 'json',
		data: wagerdata,
		
		complete: function() {
    		revertBetButton(); 
            $('#place_bet').attr('disabled', '');
            $('#fund_bet').attr('disabled', '');   	
    	},
		
		error: function(data){
			alert(data);
		},
		
		success: function(data) {
			//$('#dump').attr("innerHTML",data);
			var json = eval(data);
			if (json.type == "error"){
				alert(json.message);
                //console.log(json.maxSpreadStake);
                if (json.refreshBetSlip !== undefined)
                {
                    //alert("a");
                    getBettingSlip(undefined, '1');
                    if (parseInt($('#liveSpreadBet').val()) == 1 || parseInt($('#liveBet').val()) == 1) {
                    sleepAmount = 45;
                        clearCookieTimer = setInterval(function() {
                            $('#place_bet').text('Accept new odds (' + (sleepAmount--) + ')');
                           if (sleepAmount == -1) {
                               clearCookie();
                           } 
                            
                        }, 1000);
                    }
                }
                if (json.maxStake !== undefined)
                {
                    //console.log(json.maxStake);
                    $('#' + json.maxStake.id).val(json.maxStake.stake);
                    updateBettingSlip(json.maxStake.id);
                    $('#bet_slip_message').hide();
                }
                if (json.maxSpreadStake !== undefined)
                {
                    //getBettingSlip(undefined, '1');
                }
            } else if (json.type == "warning"){
                getBettingSlip(json.ticketId);
				alert(json.message);
			} else {
				getBettingSlip(json.ticketId);
			}
			
		}
	});
}

function clearCookie(overrideText) 
{
	//var newval = $('#marketTemplateName').val();
	//alert('blockId=' + encodeURIComponent($('#blockId').val()) + '&frmTicketId=' + ticketId);
	$.ajax({
		type: 'post',
		url: '/index.php/betting/action/clear_has_slept/',
		dataType: 'html',
		data: ''
	});
    if (typeof overrideText != 'undefined') {
        $('#place_bet').text(overrideText);
    } else {
        $('#place_bet').text('Accept new odds');
    }
    $('#place_bet').attr('disabled', '');
    $('#bet_loader').hide();
    
    if (typeof clearCookieTimer != 'undefined') {
    	clearInterval(clearCookieTimer);
    }
}

function getBettingSlip(ticketId, retryBet) {
	//var newval = $('#marketTemplateName').val();
	//alert('blockId=' + encodeURIComponent($('#blockId').val()) + '&frmTicketId=' + ticketId);
	$.ajax({
		type: 'post',
		url: $("#ajaxProvidergetBettingSlipUrl").val(),
		dataType: 'html',
		data: 'blockId=' + encodeURIComponent($('#blockId').val()) + '&frmTicketId=' + ticketId + '&userId=' + $('#usr_id').val() + '&retryBet=' + retryBet,
		
		error: function(data){
			alert(data);
		},
		
		complete: function(request, status) {
			toggleBetButton(false);
		},
		
		success: function(data) {
			//alert('blockId=' + encodeURIComponent($('#blockId').val()) + '&frmTicketId=' + ticketId);
			$('#blockBettingSlip').attr("innerHTML",data);
            
            $(".calcWinnings").each(function (index, domEle) {
                temp = $(this).attr('id').split('_');
                bet_calc = temp[1];
                slip_id = temp[2];
                stake = ($("#" + $(this).attr('id')).val());
                odds = $("#odds_"+slip_id).val();
                if (typeof odds == 'undefined'){
                    odds = 0;
                }
                var calc = (stake * odds).toFixed(2);
                if (bet_calc == 'Single' || bet_calc == 'Place'){
                    //alert("#towin_"+slip_id);
                    $("#towin_"+slip_id).val(calc);
                } else if (bet_calc == 'Singleeachway'){
                    calcEachWayTotal($(this).attr('id'));
                }
                //calcFixedSlipTotal($("#" + $(this).attr('id')));
                calcFixedSlipTotal();
            });

		}
	});
    
    

    
    
}

function switchEachWay(theId) {
	if( $('#eachwaystake_' + theId).is(':visible') ) {
        $('#eachwaystake_' + theId).hide();
        $('#straightstake_' + theId).show();
		$('#stake_Single_' + theId + '_1').val('');
		$('#towin_' + theId).val('');
		$('#stake_Singleeachway_' + theId + '_2').val('');
		$('#totalEachWay_' + theId).val('');
		
    } else {
        $('#eachwaystake_' + theId).removeClass('hidden');
        
        $('#eachwaystake_' + theId).show();
        $('#straightstake_' + theId).hide();
		$('#stake_Singleeachway_' + theId + '_2').val('');
		$('#totalEachWay_' + theId).val('');
		$('#stake_Single_' + theId + '_1').val('');
		$('#towin_' + theId).val('');
    }
	calcFixedSlipTotal();
}

function calcEachWayTotal(theId) {
    calc = (Number($('#stake_Singleeachway_' + theId + '_2').val()) * 2).toFixed(2);
    $('#totalEachWay_' + theId).val(calc);
}

function calcEachWaySingle(theId) {
    calc = (Number($('#totalEachWay_' + theId).val()) / 2).toFixed(2);
	$('#stake_Singleeachway_' + theId + '_2').val(calc);
}

function bet_note(message) {
	if ($('#bet_slip_message').length > 0) {
	    if($('#bet_slip_message').is(':visible')) {
	        $('#bet_slip_message').stop(true, true).hide();
	    }
	    
	    if (message) {
	        $('#bet_slip_message').text(message).show();
	    }
	}
}

var slipUpdatesWaiting = 0;

function updateBettingSlip(slipId, ignoreZero) 
{
    //clearCookie();
	var temp = new Array();
	var userId = $('#usr_id').val();// for normal call centre
	var userAdd = '';
	var tempUserId = $('#cashBetUserId').val(); //if defined override user id
	temp = slipId.split('_');
	if (ignoreZero === undefined)
    {
        ignoreZero = false;
    } else {
        return false;
    }

        bet_calc = temp[1];
	slip_id = temp[2];
	stake = ($("#" + slipId).val());
    
    if (stake && stake != parseFloat(stake))
    {
        bet_note(stake + ' is not a valid number. Please correct this.');
        return false;
    } else 
    {
        bet_note();
    }

	if (typeof stake == 'undefined'){
		//total calc goes here...
		var tempUserId = $('#cashBetUserId').val(); //if defined override user id
		if (typeof tempUserId != 'undefined'){
			if(tempUserId > 0) {
				//alert ('Check users balance ' + tempUserId);
			} else {
   				return false;
			}
		}
		return false;
	}
	
	if (typeof tempUserId != 'undefined'){
		userId = tempUserId;
		if(tempUserId == '0') {
                    bet_note('No Cash User Id Set!');
 
			return false;
		}
	}
	
	if (typeof userId != 'undefined'){
		userAdd = '&userId=' + userId;
	}
	
	
	odds = $("#odds_"+slip_id).val();
	if (typeof odds == 'undefined'){
		odds = 0;
	}

	var limits = eval("(" + $("#Limits_"+slip_id).val() + ")");
	if (typeof limits == 'undefined')
    {
		return false;
	} else {
		if(odds * stake > limits.maximum_win){
			var newval = limits.maximum_win / odds;
			$("#" + slipId).val(Math.floor(newval));
			stake = Math.floor(newval);
            var temp = document.getElementById(slipId);
			calcFixedSlipTotal(temp);
			bet_note("Maximum bet limit exceeded");

			//return false;
		}

		if (parseFloat(stake) < parseFloat(limits.minimum_bet) && !ignoreZero)
        {
            var temp = document.getElementById(slipId);
            calcFixedSlipTotal(temp);
			bet_note("You need to bet R" + limits.minimum_bet + " or more");
			return false;
		} else {
            bet_note();
        }
	}
    if (String(stake).indexOf(".") < String(stake).length - 3) {
        stake = Math.round(stake*100)/100;
        ($("#" + slipId).val(stake));
    }
    
    slipUpdatesWaiting++;
    toggleBetButton(true);
    
	$.ajax({
		type: 'post',
		url: $("#ajaxProviderupdateBettingSlipUrl").val(),
		dataType: 'json',
		data: 'slipId=' + slip_id + '&stake=' + stake + "&odds=" + odds + "&betCalc=" + bet_calc + userAdd,

		complete: function() {
			slipUpdatesWaiting--;
            //console.log(slipUpdatesWaiting);
            if (slipUpdatesWaiting == 0){
            	toggleBetButton(false);
            }
		},

		error: function(data){
			bet_note(data);
 		},

		success: function(data) {
			var json = eval(data);
			if (json.type == "error" && !data.suggested_stake){
				bet_note(json.message);

                                return false;
                        }
                        else if (json.type == "error" && data.suggested_stake) {

                            
                            if (data.suggested_stake < 0)
                            {
                                $("#" + slipId).val(0);
                                bet_note("Unfortunately no more wagers can be taken on these odds at this time, please try again later.");
                                return updateBettingSlip(slipId, true); 
                            } else {
                                bet_note(json.message);
                                $("#" + slipId).val(data.suggested_stake);
                            }
                            
                            
                        }
                        //$('#bet_slip_message').hide();
                        
                        var calc = (stake * odds).toFixed(2);
				if (bet_calc == 'Single' || bet_calc == 'Place'){
					$("#towin_"+slip_id).val(calc);
				} else if (bet_calc == 'Singleeachway'){
					calcEachWayTotal(slip_id);
				}
				calcFixedSlipTotal($("#" + slipId));
				//total calc goes here...
				var tempUserId = $('#cashBetUserId').val(); //if defined override user id
				if (typeof tempUserId != 'undefined'){
					if(tempUserId > 0) {
						//alert ('Check users balance ' + tempUserId);
					} else {
						bet_note('No user id set for cash bets!');
						return false;
					}
				}
            
		}
	});

    
}

function calcFixedSlipTotal(callingElement){
	var singleTotal = 0;
	var multiTotal = 0;
	var minLimit = 0;
	var minLimitMulti = 0;
	var largestOdds = 0;
	var temp = Array();
    $('#stakeTable input').each(function(idx, item) {  
		if (item.id.indexOf('stake') >= 0){
			temp = item.id.split('_');
			if ($("#eachway_" + temp[2]).is(':checked')){
				if (item.id.indexOf('Singleeachway') >= 0){
					singleTotal += Number($("#totalEachWay_" + temp[2]).val());
				}
			} else {
				singleTotal += Number(item.value); 
            }
		}
        
		if (typeof temp[2] != 'undefined'){
			var limits = eval("(" + $("#Limits_"+temp[2]).val() + ")");
			if(minLimit == 0 || limits.maximum_win < minLimit){
				minLimit = limits.maximum_win;
			}
			if(minLimitMulti == 0 || limits.maximum_win_multiple < minLimitMulti){
				minLimitMulti = limits.maximum_win_multiple;
			}
		}

    });
    
    /*$('#multiTable').find(':input').each(function() {
		if (this.id.indexOf('stake') >= 0){
			temp = this.id.split('_');
			multiTotal += Number(temp[3] * this.value);
		}

		if (this.id.indexOf('largestOdds') >= 0){
			temp = this.id.replace('largestOdds','stake');
			if (largestOdds < this.value){
				largestOdds = this.value;
			}
			alert (temp);
			$('#' + temp).val(999);
			alert($('input#' + temp).val());
			if (($('input#' + temp).val() * this.value) > minLimitMulti){
				alert("multi exceeds limit");
				return false;
			}
			return false;
		}


    });*/

	/*$('#element').data({'id' : this.attr('id')});

	$.data('#element').id;*/


	$('#multiTable').find(':input').each(function(){
		if(this.id.indexOf('stake') >= 0) {

			var temp = this.id.split('_');
			multiTotal += Number(temp[3] * this.value);
			//alert(temp + ':' + this.value);
			//$('#' + this.id).data({'value' : this.value});
		}

		if (this.id.indexOf('largestOdds') >= 0){
			temp = this.id.replace('largestOdds','stake');
			if (largestOdds < parseFloat(this.value)){
				largestOdds = this.value;
			}
			var oddsToUse = this.value;
			if (parseInt(this.value) == 0){
				oddsToUse = largestOdds;
			}

			//alert($("input[rel='" + this.id + "']").val());
			if (($("input[rel='" + this.id + "']").val() * oddsToUse) > minLimitMulti){
				var newval = minLimitMulti / oddsToUse;
				
                if (!this.id.indexOf('Takeback'))
                {
                    $("input[rel='" + this.id + "']").val(Math.floor(newval));
                    alert("Maximum multiple bet limit exceeded");
                }
			}
		}
    });
	
	/*	if(this.id.indexOf('largestOdds') >= 0){
			temp = this.id.replace('largestOdds','stake');
			if (largestOdds < this.value){
				largestOdds = this.value;
			}
			alert (temp);
			$('#' + temp).val(999);
			alert($('#' + temp).val());
			if (($('#' + temp).val() * this.value) > minLimitMulti){
				alert("multi exceeds limit");
				return false;
			}
			return false;
		}

	});*/

	/*if (minLimit < multiTotal){
		alert("exceeds limit");
		return false;
	}*/
    if (callingElement !== undefined)
    {
        if (callingElement.value !== undefined)
        {
            var oldVal = callingElement.value;
        } else
        {
            var oldVal = callingElement.val();
        }
        if(oldVal.indexOf(".") > -1)
        {
            if(oldVal.length - (oldVal.indexOf(".")+1) > 2)
            {
                callingElement.value = Math.round(oldVal * 100) / 100 ;
            }
        }
    }
    
	var Total = Number(singleTotal) + Number(multiTotal);
	$('#totalStake').html(Total.toFixed(2));
}

function updateBettingSlipMulti(slipId) {
	var temp = new Array();
	temp = slipId.split('_');
	
	slip_id = temp[1];
	stake = $("#stake_"+slip_id).val();
	odds = $("#odds_"+slip_id).val();


	$.ajax({
		type: 'post',
		url: $("#ajaxProviderupdateBettingSlipMultiUrl").val(),
		dataType: 'json',
		data: 'slipId=' + slip_id + '&stake=' + stake + "&odds=" + odds,
		
		complete: function() {
			getBettingSlip();
		},
		
		error: function(data){
			alert(data);
		},		

		success: function(data) {			
			var json = eval(data);
			if (json.type == "error"){
				alert(json.message);
			}		
		}
	});	
}

function removeAllWager(parent_id){
	proceed = confirm("Are you sure you want to delete all wagers?");
	if(proceed){
		toggleBetButton(true);
		
		$.ajax({
			type: 'post',
			url: $("#ajaxProviderremoveAllWagerUrl").val(),
			dataType: 'json',
			data: 'parentId=' + parent_id,		
			complete: function() {
				getBettingSlip();
			},
			error: function(data){
				alert(data);
			},		
			success: function(data) {
				var json = eval(data);			
				if (json.type == "error"){
					alert(json.message);
				}		
			}
		});
	} else {
		
	}
}

function cancelWager(id,proceed){
	if (!proceed){
	proceed = confirm("Are you sure you want to delete this wager?");
	}
	if(proceed){
		toggleBetButton(true);
		
		$.ajax({
			type: 'post',
			url: $("#ajaxProviderCancelWagerUrl").val(),
			dataType: 'json',
			data: 'wagerId=' + id,		
			complete: function() {
				getBettingSlip();
			},
			error: function(data){
				alert(data);
			},		
			success: function(data) {
				var json = eval(data);			
				if (json.type == "error"){
					alert(json.message);
				}		
			}
		});
	}
    clearCookie($('#place_bet').text());
}
		
function confirmWagerChanges(removeIds,updateIds,retryBet){
    
	if(updateIds){
		$.ajax({
			type: 'post',
			url: $("#ajaxProviderConfirmOddsChangeUrl").val(),
			dataType: 'json',
			data: 'wagerId=' + updateIds,
			complete: function() {
				if (!removeIds){
					getBettingSlip();
            }
			},
			error: function(data){
				alert(data);
			},
			success: function(data) {
				var json = eval(data);
				if (json.type == "error"){
					alert(json.message);
                }
			}
		});
	}
	if (removeIds){
		cancelWager(removeIds,true);
	}
    if (retryBet !== undefined && retryBet)
    {
        addWager();
    }
    clearCookie();
}

function cancelWagerMulti(mId){
	$.ajax({
			type: 'post',
			url: $("#ajaxProvidercancelWagerMultiUrl").val(),
			dataType: 'json',
			data: 'mId=' + mId,		
			complete: function() {
				getBettingSlip();
			},
			error: function(data){
				alert(data);
			},		
			success: function(data) {
				
						
			}
		});
}

function changeMarketStatus(marketId, curStat){
	$.ajax({
			type: 'post',
			url: $("#ajaxProviderchangeMarketStatusUrl").val(),
			dataType: 'json',
			data: 'marketId=' + marketId + '&curStat=' + curStat + '&module=fixed',		
			error: function(data){
				alert(data);
			},		
			success: function(data) {				
				window.location.reload();		
			}
		});		
}

function changeEventStatus(eventId, curStat){
	$.ajax({
			type: 'post',
			url: $("#ajaxProviderchangeEventStatusUrl").val(),
			dataType: 'json',
			data: 'eventId=' + eventId + '&curStat=' + curStat,		
			error: function(data){
				alert(data);
			},		
			success: function(data) {				
				window.location.reload();		
			}
		});
}

function updateMarketOptions(marketId){
     var wagerdata = '';
	
    $.ajax({
		type: 'post',
		url: $("#marketOptionsURL").val(),
		dataType: 'json',
		data: 'eventId=' + $("#event_id").val() + '&marketId=' + $("#event_market").val(),
		
		error: function(data){
			alert(data);
		},
		
		success: function(data) {
            $("#market_category_conflict").attr('checked', false);
			var json = eval(data);
            //$.each(this.aFields, function(i) {
			$.each(json, function(key, value){
                if (key == 'market_category_conflict')
                {
                    if (value == 1)
                    {
                        $("#" + key).attr('checked', true);
                    } 
                } else {
                    $("#" + key).val(value);
                }
                

            });

		}
	});
}

function updateMaxExposureByOddsId(oddsId){
     var wagerdata = '';

    $.ajax({
		type: 'post',
		url: $("#exposureUpdateURL").val(),
		dataType: 'json',
		data: 'frmOddsId=' + oddsId + '&frmExposure=' + $("#exposure_" + oddsId).val(),

		error: function(data){
			alert(data);
		},

		success: function(data) {
			var json = eval(data);
            $('#ajaxMessage').attr("innerHTML",'<p class="message-'+json.type+'">'+json.message+'</p>');
			$("#ajaxMessage").fadeIn("slow");
			$("#ajaxMessage").fadeOut(5000);
		}
	});
}

function updateMaxExposureBySpreadMarketId(marketId){
     var wagerdata = '';

    $.ajax({
		type: 'post',
		url: $("#s_exposureUpdateURL").val(),
		dataType: 'json',
		data: 'frmMarketId=' + marketId + '&frmExposure=' + $("#s_exposure_" + marketId).val(),

		error: function(data){
			alert(data);
		},

		success: function(data) {
			var json = eval(data);
            $('#ajaxMessage').attr("innerHTML",'<p class="message-'+json.type+'">'+json.message+'</p>');
			$("#ajaxMessage").fadeIn("slow");
			$("#ajaxMessage").fadeOut(5000);
		}
	});
}

function updateMaximumWin(tableName, id, element){
    $.ajax({
		type: 'post',
		url: $("#maximumWinUpdateURL").val(),
		dataType: 'json',
		data: 'frmId=' + id + '&frmTable=' + tableName + '&frmMaximumWin=' + $("#" + element).val(),

		error: function(data){
			alert(data);
		},

		success: function(data) {
			var json = eval(data);
            $('#ajaxMessage').attr("innerHTML",'<p class="message-'+json.type+'">'+json.message+'</p>');
			$("#ajaxMessage").fadeIn("slow");
			$("#ajaxMessage").fadeOut(5000);
		}
	});
}


function fundWager(betType) {

    /*var wagerdata = '';  
	var noContinue = 0;
    var noSingleContinue = 0;
    var noMultiContinue = 0;
	var temp = Array();
    $('#stakeTable input').each(function(idx, item) {  
		if (item.id.indexOf('stake') >= 0){
			temp = item.id.split('_');
			if (item.value < 1){
				//alert ("Your stake must be higher than 1");
				//noSingleContinue = 1;
				//return false;
			} else {
                //wagerdata += "stake[" + temp[1] + "][value]=" + item.value + "&stake[" + temp[1] + "][odds]=" + $("#odds_" + temp[1]).val() + "&";
                if ($("#eachway_" + temp[3]).is(':checked')){
                    wagerdata += "stakeType[|" + temp[1] + "][" + temp[2] + "][value]=" + item.value + "&stakeType[|" + temp[1] + "][" + temp[2] + "][count]=" + temp[3] + "&";
                } else {
                    wagerdata += "stakeType[|" + temp[1] + "][" + temp[2] + "][value]=" + item.value + "&stakeType[|" + temp[1] + "][" + temp[2] + "][count]=" + temp[3] + "&";
                }
                
            }
		}
        
    });
    
    $('#multiTable input').each(function(idx, item) {  
		if (item.id.indexOf('stake') >= 0){
			temp = item.id.split('_');
			if (item.value < 1){
				//alert ("Your stake must be higher than 1");
				//noMultiContinue = 1;
				//return false;
			} else {
                wagerdata += "stakeType[" + temp[1] + "][" + temp[2] + "][value]=" + item.value + "&stakeType[" + temp[1] + "][" + temp[2] + "][count]=" + temp[3] + "&";
            }
		}
        
    });

    if (noSingleContinue && noMultiContinue){
        noContinue = 1;
    }
	//alert(wagerdata); 
	
	if (wagerdata == ""){
		alert("You need to bet on something. Please ensure that your stake is higher than the minimum amount.");
		return false;
	}
	if (noContinue){
		return false;
	}
    $.ajax({
		type: 'post',
		url: $("#ajaxProviderFundWagerUrl").val(),
		dataType: 'json',
		data: wagerdata,
		
		error: function(data){
			alert(data);
		},
		
		success: function(data) {
			var json = eval(data);
			if (json.type == "error"){
				alert(json.message);
			} else {
				//getBettingSlip(json.ticketId);
			}
			
		}
	});*/
	$('#betType').val(betType);
	toggleFunding();

}

function getGateways(gateway, isAjax){
	if ($('#totalStake').html() != ''){
		$('#gatewayform').load('/index.php/user/?action=getGateways&gateway='+gateway+'&ajax=' + Number(isAjax) + '&amount=' + encodeURIComponent($('#totalStake').html()) + '&betType=' + $('#betType').val());
	} else {
		$('#gatewayform').load('/index.php/user/?action=getGateways&gateway='+gateway+'&ajax=' + Number(isAjax));	
	}
}

function toggleFunding(){
	$('#betInfo').toggle();
	$('#funding').toggle();
}

function addToSlip(actionId){

    var temp = actionId.split('_');

    if ($("#stake_" + temp[1]).val() < 1){
                alert ("Your stake must be higher than 1");
                noContinue = 1;
                return false;
        }

    var json = eval($("#" + actionId).val());

    marketdata = 'aMarket[action]=' + json.action + '&aMarket[low]=' + json.action + '&aMarket[high]=' + json.action + '&aMarket[stake]=' + $("#stake_" + temp[1]).val() + '&aMarket[marketId]=' + temp[1] + '&';
    $.ajax({
            	type: 'post',
                url: $("#ajaxProvideraddToSlipUrl").val(),
                dataType: 'json',
                data: marketdata,

                error: function(data){
                        alert(data);
                },

                success: function(data) {
                        var json = eval(data);
                        if (json.type == "error"){
                                alert(json.message);
                        } else {
                //alert(json.message);
                                getSpreadBettingSlip();
                        }

                }
        });

}


