var sMessage;
var mostRecentAjaxRequest = false;
var intBetslipFixedItemHeightTotal = 376;
var intBetslipVariableItemHeightTotal = 0;
var intNumberOfDynamicSections = 0;
var intBetSlipHeight;
var strNewBetSlipHeight;
var blnIe6Detected = (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1);

var BetSlip_firstLoad_done = false;

//$(document).ready(BetSlip_firstLoad);
$(document).ready(BetslipLoad_AjaxRequest);

/*************************************************/

//function BetSlip_firstLoad() {
//    if (!BetSlip_firsgtLoad_done) { 
//        BetSlip_firstLoad_done = true;

//        if ($("#bet-slip-loading") == null)
//            return;

//        $("#bet-slip-loading").bind("ajaxStart", ShowLoading);
//        $("#bet-slip-loading").bind("ajaxStop", HideLoading);
//        BetslipLoad_AjaxRequest();
//    }
//}

function BetslipSubmit_AjaxRequest(options) {

    var url;
    var formName;
    
    if (!options) {
        options = {};
    }
    if (!options.url) {
        url = "/BetSlip/BetSlip.aspx";
    } else {
        url = options.url;
    }
    if (!options.formName) {
        formName = "BetSlipForm";
    } else {
        formName = options.formName;
    }

    $.cookie("IASBetSlipOpen", "true");

    var frm = document.getElementById(formName);
    if (frm != null) {
        var el = document.createElement("input");
        el.type = "hidden";
        el.name = "Action";
        el.value = "Parse";
        frm.appendChild(el);

        GetBetSlipData(url, formName);
        ShowLoading();

        frm.removeChild(el);
        frm.target = "";
    }
    
//    var date = new Date();
//    var thisRequest = date.getTime();
//    mostRecentAjaxRequest = thisRequest;

//    var datastring = "Action=Parse&r=" + thisRequest;
//    datastring = datastring + "&" + $("#" + formName).serialize();

//    $.ajax({
//        url: url,
//        type: "POST",
//        success: function(data) { if (thisRequest == mostRecentAjaxRequest) { BB_LoadNewHtmlIntoPage(data); } },
//        dataType: "html",
//        error: BetSlip_HandleError,
//        data: datastring
//    });
//

}


function BetslipLoad_AjaxRequest() {
    GetBetSlipData("/betslip/betSlip.aspx", "betSlipFrameForm");
    ShowLoading();

//       var date = new Date();
//       var thisRequest = date.getTime();
//       mostRecentAjaxRequest = thisRequest;

//       $.ajax({
//           url: "/BetSlip/BetSlip.aspx?Action=Load&r=" + thisRequest,
//           type: "GET",
//           success: function(data) { if (thisRequest == mostRecentAjaxRequest) { BB_LoadNewHtmlIntoPage(data); } },
//           dataType: "html",
//           error: BetSlip_HandleError
//       });
//

}



function BetSlip_HandleError(request,error) {
    // commenting this out because this error will display when someone clicks away from the page
    // while the betslip is loading which occurs frequently in test environments where the network latency is high
    //alert("The following error has occured. Please notify Client Services. Error: " + error);
}

function ShowLoading() {
    $("#bet-slip-loading").show();
}

function HideLoading (){
    $("#bet-slip-loading").hide();
}
   
   
   function BB_BetslipRemove(dataString, strUniqueStakeId) {
       var date = new Date();
       $(".remove-selection > a").unbind("click").attr("onclick", "").addClass("disabled");

       // need to update the stakes cookie to remove the relevant stake value
       if (strUniqueStakeId) {
           // if the row id is 0 then remove all - reset entire cookie
           if (strUniqueStakeId == 0) {
               $.cookie("IASStakes", "");
           }
           else {
               // reset the removed stake value;
               var eleRemoveInput = $("#pre-game-selections input[uniqueid=" + strUniqueStakeId + "]");
               if (eleRemoveInput.length == 1) {
                   eleRemoveInput[0].value = "";
                   eleRemoveInput[0].onkeyup();
               }
               // update the cookie
               StoreUnsavedStakes();
           }
       }
       var url = "/betslip/BetSlipRemove.aspx?" + dataString;
       GetBetSlipData(url, "betSlipFrameForm");
       ShowLoading();

       
//       var thisRequest = date.getTime();
//       mostRecentAjaxRequest = thisRequest;
//
//        $.ajax({
//            url: "/BetSlip/BetSlipRemove.aspx?r=" + thisRequest,
//            type: "GET",
//            success: function(data) {
//                if (thisRequest == mostRecentAjaxRequest) {
//                    BB_LoadNewHtmlIntoPage(data);
//                } 
//            },
//            dataType: "html",
//            error: BetSlip_HandleError,
//            data: dataString
//        });


   }

   function BB_LoadNewHtmlIntoPage(data) {
       var strBetslipOpen = "";

       //$("#betslip").html(data);
       var frm = document.getElementById("betslip");
       if (frm == null) return;

       frm.innerHTML = data;
       
       // check to see if the user has been logged out
       if ($("#bet-slip-container #logged-out").length > 0) {
           // if the logged out version of the login panel is not present
           if ($("#login-panel #logged-out").length == 0) {
               window.location.reload();
           }
       }

       // if we are on the receipt page - then update the Account Balance
       if ($("#bet-slip-container #receipt-message").length > 0) {
           $.ajax({
               url: "/XMLData/GetAccountBalance.aspx",
               type: "GET",
               success: function(data) { $("#account-balance-amount").html(data); },
               dataType: "html",
               cache: false
           }); 
       }
       
       Betslip_Init();
       CalcTotalBet();
       Betslip_PopulatePendingStakes();
       strBetslipOpen = $.cookie("IASBetSlipOpen");

       if (strBetslipOpen == "true") {
           Betslip_OpenBetslip(false);
       }

       HideLoading();
       mostRecentAjaxRequest = false;
       
       $(document).ready(function() {
           $("#bet-slip-container").keypress(
           // block default enter key functionality unless SubmitMe function exists
            function(e) {
                var intKey;
                if (window.event) {
                    intKey = window.event.keyCode; //IE
                }
                else {
                    intKey = e.which; //firefox      
                }

                if (intKey == 13) {
                    if (typeof (SubmitMe) == "function") {
                        SubmitMe(0);
                        e.returnValue = false;
                        return false;
                    }
                }
            }
            );
       });
   }

   function Betslip_ScrollToLatestBet() {
       // Special case for IE6 because this scrolling was causing problems making the betslip content disappear.
       if (!blnIe6Detected) {
            $("#bet-slip-body .table-container").each(function() { $(this).scrollTo($("#bet-slip-body .last-row"), { duration: 100 }); });
       } else {
            $("#bet-slip-body .table-container").attr({ scrollTop: $("#bet-slip-body .table-container").attr("scrollHeight") });
       }
   }


/*
function SubmitOnly()
{
		if (document.getElementById("__aspnetForm") !=null) {
			document.getElementById("__aspnetForm").submit();

        }
        else if (document.getElementById("aspnetForm") != null) {
            document.getElementById("aspnetForm").submit();
        }
        else if (document.getElementById("frmRacingBetSlip") != null) {
            document.getElementById("frmRacingBetSlip").submit();
		}
}*/
	
function SubmitMe()
{
	if (BetSlip_ValidateBet()) {
	    if (BetSlip_ConfirmChecked()) {
	        document.getElementById("hidBet").value = "1";

	        BetslipSubmit_AjaxRequest();
	    }
	}
	else
		alert(sMessage);
}

function BetSlip_ConfirmChecked() {
    if ($("#BetSlip_confirm").length > 0) {
        if (!$("#BetSlip_confirm")[0].checked) {
            alert(CLIENT_ResourceString_Global.BetSlip_Error_NotConfirmed);
            return false;
        }
    }
    return true;
}

function BetSlip_ValidateBet() {
	var bettype = '';
	var runner = '';
	var stake = 0;
	var entered = 0;

	sMessage = '';
	/*
	if (document.getElementById("chkBetslipValidateConfirmation") !=null)
	{
		if (document.getElementById("chkBetslipValidateConfirmation").checked==false)
		{
			sMessage = CLIENT_ResourceString_Global.BetslipValidateConfirmationPopup;
		}
	}*/
	
	
	var tbl = document.getElementsByTagName("input");
	for (var i = 0; i < tbl.length; i++)
	{
		if ((tbl[i].id.indexOf("Stake_Row") >= 0) || (tbl[i].id.indexOf("Unit_Pkg") >= 0) || (tbl[i].id.indexOf("Unit_Exotic") >= 0) || (tbl[i].id.indexOf("Stake_Multi_Teaser") >= 0))
		{
			bettype = tbl[i].alt;
			runner = tbl[i].title;
			stake = tbl[i].value;
			if (stake.length != 0) {
				if (!(/^[0-9,.]{1,12}$/.test(stake))) {
				    sMessage = sMessage + CLIENT_ResourceString_Global.Racing_Client_Error_InvalidStakeAmtForRunner + ' ' + runner + '. ' + CLIENT_ResourceString_Global.Racing_Client_Error_PleaseReenter + '\n';
				}
				if (stake == 0) {
				    sMessage = sMessage + CLIENT_ResourceString_Global.Racing_Client_Error_StakeAmtCannotBeZero + ' ' + runner + '. ' + CLIENT_ResourceString_Global.Racing_Client_Error_PleaseReenter + '\n';
				}
				if (bettype == "WIN" || bettype == "PLC" || bettype == "LINE") {
					if (stake < 1) {
					    sMessage = sMessage + CLIENT_ResourceString_Global.Racing_Client_Error_StakeAmtGreaterOne + ' ' + runner + ' ! ' + CLIENT_ResourceString_Global.Racing_Client_Error_PleaseReenter + '\n';
					}
				}            					
				else if (bettype == "QIN" || bettype == "TFA" || bettype == "F4" || bettype == "EXA") 
				{
					if (stake < .5) {
					    sMessage = sMessage + CLIENT_ResourceString_Global.Racing_Client_Error_StakeAmtGreaterThan50Cents + ' ' + CLIENT_ResourceString_Global.Racing_Client_Error_PleaseReenter + '\n';
					}
					else if ((stake % .5) != 0) {
					sMessage = sMessage + CLIENT_ResourceString_Global.Racing_Client_Error_StakeIn50CentInc + ' ' + CLIENT_ResourceString_Global.Racing_Client_Error_PleaseReenter + '\n';
					}
				} 
				else if ((bettype == "MULTI_Multibet") || (bettype == "MULTI_UpSell")) {
					if (stake < 1) {
					    sMessage = sMessage + CLIENT_ResourceString_Global.Racing_Client_Error_StakeAmtGreaterOne + ' ' + runner + ' ! ' + CLIENT_ResourceString_Global.Racing_Client_Error_PleaseReenter + '\n';
					}
				}           					
				else if ((bettype == "PACKAGE")) {
					if (stake < .5) {
					    sMessage = sMessage + CLIENT_ResourceString_Global.Racing_Client_Error_StakeIn50CentInc + ' ' + runner + ' ! ' + CLIENT_ResourceString_Global.Racing_Client_Error_PleaseReenter + '\n';
					}
				}           	
				entered++;			
			}
		}
	}
	
	if (entered == 0)
	    sMessage = CLIENT_ResourceString_Global.Racing_Client_Error_StakeNeedEntered + '!\n';
if (sMessage == '')

		return true;
	else 
		return false;
}

function AdjustStakeToWin(RowId,CtrlName,iPrice)
{
	var iValue = 0.0;
	var iCalcValue = 0.0;
	var iStake = 0.0;
	var sPoints= '';
	var aPoints;
	var bToWin = false;

	if (document.getElementById('ToWin_Row' + RowId) != null) {
		bToWin = true;
	}
	
	// Points Exist
	if (document.getElementById('PointsAdjust_Row' + RowId) != null)
	{
			sPoints = document.getElementById('PointsAdjust_Row' + RowId).value;
			aPoints = sPoints.split("^");
			iPrice = aPoints[4];
	}
	if (iPrice > 0) {
		switch (CtrlName) 
		{
			case 'PointsAdjust_Row':
						if (bToWin) {
								iStake = document.getElementById('Stake_Row' + RowId).value;
								iCalcValue = (iStake * iPrice) - iStake;
								if (iCalcValue > 0) 
									document.getElementById('ToWin_Row' + RowId).value = iCalcValue.toFixed(2);
								else
									document.getElementById('ToWin_Row' + RowId).value = '';
						}
						break;
	/*					
		case 'Stake_Row': 
						if (bToWin) {
								iStake = document.getElementById('Stake_Row' + RowId).value;
								iCalcValue = (iStake * iPrice) - iStake;
								if (iCalcValue > 0) 
									document.getElementById('ToWin_Row' + RowId).value = iCalcValue.toFixed(2);
								else
									document.getElementById('ToWin_Row' + RowId).value = '';
						}
						break;
			*/

		case 'Stake_Row':
		    if (bToWin) {
		        iStake = document.getElementById('Stake_Row' + RowId).value;

		        iCalcValue = (iStake * iPrice) - iStake;

		        if (document.getElementById('EW_Row' + RowId.split("-").reverse()[0]).value == 1) {
		            iCalcValue = (iStake * iPrice) - (2 * iStake);
		        }

		        if (iCalcValue > 0)
		            document.getElementById('ToWin_Row' + RowId).value = iCalcValue.toFixed(2);
		        else
		            document.getElementById('ToWin_Row' + RowId).value = '';
		    }
		    break;
						
		/*			
			case 'ToWin_Row': 
						iCalcValue = document.getElementById('ToWin_Row' + RowId).value / (iPrice - 1);
						if (iCalcValue > 0) 
							document.getElementById('Stake_Row' + RowId).value = iCalcValue.toFixed(2);
						else 
							document.getElementById('Stake_Row' + RowId).value='';
						break;
						
*/
			case 'ToWin_Row': 
						if (document.getElementById('EW_Row' + RowId.split("-").reverse()[0]).value == 1)
							iCalcValue = document.getElementById('ToWin_Row' + RowId).value / (iPrice - 2);
						else
							iCalcValue = document.getElementById('ToWin_Row' + RowId).value / (iPrice - 1);
							
						if (iCalcValue > 0) 
							document.getElementById('Stake_Row' + RowId).value = iCalcValue.toFixed(2);
						else 
							document.getElementById('Stake_Row' + RowId).value='';
						break;

			case 'Stake_Multi_UpSell': 
					iStake = document.getElementById('Stake_Multi_UpSell').value;
					iCalcValue = (iStake * iPrice) - iStake;
					if ((iCalcValue > 0) && (document.getElementById('ToWin_Multi_UpSell') != null)) {
						document.getElementById('ToWin_Multi_UpSell').value = iCalcValue.toFixed(2);
					}
					break;
			case 'ToWin_Multi_UpSell': 
					iCalcValue = document.getElementById('ToWin_Multi_UpSell').value / (iPrice - 1);
					if (iCalcValue > 0) 
						document.getElementById('Stake_Multi_UpSell').value = iCalcValue.toFixed(2);
					else
						document.getElementById('Stake_Multi_UpSell').value = '';
					break;
			case 'Stake_Multi_Multibet': 
					iStake = document.getElementById('Stake_Multi_Multibet').value;
					iCalcValue = (iStake * iPrice) - iStake;
					if ((iCalcValue > 0) && (document.getElementById('ToWin_Multi_Multibet') != null)) {
						document.getElementById('ToWin_Multi_Multibet').value = iCalcValue.toFixed(2);
					}
					break;
			case 'ToWin_Multi_Multibet': 
					iCalcValue = document.getElementById('ToWin_Multi_Multibet').value / (iPrice - 1);
					if (iCalcValue > 0) 
						document.getElementById('Stake_Multi_Multibet').value = iCalcValue.toFixed(2);
					else
						document.getElementById('Stake_Multi_Multibet').value = '';
					break;
			case 'Stake_Multi_Teaser': 
					iStake = document.getElementById('Stake_Multi_Teaser').value;
					iCalcValue = (iStake * iPrice) - iStake;
					if ((iCalcValue > 0) && (document.getElementById('ToWin_Multi_Teaser') != null)) 
						document.getElementById('ToWin_Multi_Teaser').value = iCalcValue.toFixed(2);
					else
						document.getElementById('ToWin_Multi_Teaser').value = '';
					break;
			case 'ToWin_Multi_Teaser': 
					iCalcValue = document.getElementById('ToWin_Multi_Teaser').value / (iPrice - 1);
					if (iCalcValue > 0) 
						document.getElementById('Stake_Multi_Teaser').value = iCalcValue.toFixed(2);
					else
						document.getElementById('Stake_Multi_Teaser').value = '';

					break;
		}
	}
	CalcTotalBet();
}

function AdjustExoticStakeToWin(RowId,CtrlName,iPrice)
{
	var iValue = 0.0;
	var iCalcValue = 0.0;
	var iStake = 0.0;
	
	if (iPrice > 0) {
		HideToWin();
		switch (CtrlName) 
		{
			case 'Unit_Exotic': 
				iStake = document.getElementById('Unit_Exotic' + RowId).value;
				iCalcValue = (iStake * iPrice);
				if (iCalcValue > 0) {
					if (document.getElementById('Exotic' + RowId) != null) {
						document.getElementById('Exotic' + RowId).value = iCalcValue.toFixed(2);
					}
					if (document.getElementById('Stake_Exotic' + RowId) != null) {
						document.getElementById('Stake_Exotic' + RowId).value = iCalcValue.toFixed(2);
					}
				}
				else{
					if (document.getElementById('Exotic' + RowId) != null) {
						document.getElementById('Exotic' + RowId).value = "";
					}
					if (document.getElementById('Stake_Exotic' + RowId) != null) {
						document.getElementById('Stake_Exotic' + RowId).value = 0;
					}
				}
				break;
			case 'Stake_Exotic':
				iStake = document.getElementById('Exotic' + RowId).value;
				iCalcValue = Math.floor(iStake * 100 / iPrice) / 100 ;
				iStake = iCalcValue * iPrice;
				
				if (iCalcValue >= 0.01) {
					if (document.getElementById('Unit_Exotic' + RowId) != null) {
						document.getElementById('Unit_Exotic' + RowId).value = iCalcValue;
					}
					if (document.getElementById('Stake_Exotic' + RowId) != null) {
						document.getElementById('Stake_Exotic' + RowId).value = iStake.toFixed(2);
					}
				}
				else{
					if (document.getElementById('Unit_Exotic' + RowId) != null) {
						document.getElementById('Unit_Exotic' + RowId).value = "";
					}
					if (document.getElementById('Stake_Exotic' + RowId) != null) {
						document.getElementById('Stake_Exotic' + RowId).value = 0;
					}
				}
				break;
		}
	}
	CalcTotalBet();
}


function AdjustPackage(NameSuffix,Bets,Return)
{
	var iStake = document.getElementById('Unit_Pkg^' + NameSuffix).value;
	if (!isNaN(iStake)) {
		if (document.getElementById('Stake_Pkg^' + NameSuffix) != null) {
			document.getElementById('Stake_Pkg^' + NameSuffix).value = (Bets * iStake).toFixed(2);
		}
		if (document.getElementById('Stake_Span^' + NameSuffix) != null) {
			document.getElementById('Stake_Span^' + NameSuffix).innerHTML = (Bets * iStake).toFixed(2);
		}
		if (document.getElementById('ToWin_Pkg^' + NameSuffix) != null) {
			document.getElementById('ToWin_Pkg^' + NameSuffix).value = (iStake * (Return - Bets)).toFixed(2);
		}
		else {
			HideToWin();
		}
		if (document.getElementById('ToWin_Span^' + NameSuffix) != null) {
			document.getElementById('ToWin_Span^' + NameSuffix).innerHTML = (iStake * (Return - Bets)).toFixed(2);
		}
		else {
			HideToWin();
		}
		CalcTotalBet();	
	}
}

function CalcTotalBet() {
	var ExoticStake = 0.0;
	var TotalStake = 0.0;
	var TotalToWin = 0.0;
	var iPos = 0;
	var showExoticStake = false;

	var tbl = document.getElementsByTagName("INPUT");
	for (var i = 0; i < tbl.length; i++)
	{
		if (!showExoticStake) {
			if (tbl[i].id.indexOf("Unit_Exotic") >= 0) {
				if (tbl[i].value.length > 0 && !isNaN(tbl[i].value) && (tbl[i].value % 0.5 != 0)) {
					showExoticStake = true;
				}
			}
		}
		if (tbl[i].id.indexOf("Stake_Exotic") >= 0) {
			ExoticStake += 1*tbl[i].value;
		}

//		if (tbl[i].id.indexOf("Stake_") >= 0) {
//		  if (document.getElementById('EW_Row' + tbl[i].id.slice(18)) != null) 
//				TotalStake += 2*tbl[i].value;}
//		  else{
//				TotalStake += 1*tbl[i].value;}
//		}


		if (tbl[i].id.indexOf("Stake_") >= 0) {

		tmp = tbl[i].id;
		temp_Row = tmp.substr(tmp.lastIndexOf("_"), 4);
		tmpArr = tmp.split("-");
		tmpEW_Row = 'EW' + temp_Row + tmpArr.reverse()[0];
		
		if (document.getElementById( tmpEW_Row ) != null ){
		
			if (document.getElementById( tmpEW_Row ).value == 1 )
					TotalStake += 2*tbl[i].value;
			else
					TotalStake += 1*tbl[i].value;
		}
		 else
             TotalStake += 1*tbl[i].value;
		
		}
		if (tbl[i].id.indexOf("ToWin_") >= 0) {
			TotalToWin += 1*tbl[i].value;
		}
	}
	if (document.getElementById('exoticstotal') != null) {
		if (showExoticStake) {
			document.getElementById('exoticstotal').style.display = 'block';
			document.getElementById('Total_Exotics').innerHTML = (ExoticStake).toFixed(2);
		}
		else {
			document.getElementById('exoticstotal').style.display = 'none';
		}
	}
	if (document.getElementById('Total_Stake') != null) {
		document.getElementById('Total_Stake').innerHTML = (TotalStake).toFixed(2);
	}
	if ((document.getElementById('Total_ToWin') != null) && (document.getElementById('Total_ToWin_Label').innerHTML != '')) {
		document.getElementById('Total_ToWin').innerHTML = (TotalToWin).toFixed(2);
	}
}

// stores unsaves stakes in the single selections into the cookie
function StoreUnsavedStakes() {
    var objSingleSelectionStakeInputs = $("#pre-game-selections input[uniqueid]");
    var strSelectionCookie = "";
    
    objSingleSelectionStakeInputs.each(function(i) {
        // if the value is not blank
        if (this.value != "")
        {
            // store the stake in the cookie (uses the unique guid then = and the value of the stake)
            strSelectionCookie += $(this).attr("uniqueid") + "=" + (this.value) + "|";
        }
    });
    
    $.cookie("IASStakes", strSelectionCookie);
}

function HideToWin()
{
		document.getElementById('Total_ToWin_Label').innerHTML='';
		document.getElementById('Total_ToWin').innerHTML = '';
}

function resizeBetSatus() {
//		var bsbody = document.getElementById("bsbody");
//		var bstable = document.getElementById("bstable");
//		if (bsbody != null && bstable != null) {
//			if (bsbody.offsetHeight > (document.body.clientHeight - 250)) {
//				bsbody.style.height = (document.body.clientHeight - 250) + "px";
//				bsbody.style.overflow = "auto";
//				bstable.style.width = "180px";
//			}
//			else {
//				bsbody.style.height = "auto";
//				bsbody.style.overflow = "visible";
//				bstable.style.width = "198px";
//			}
//		}
}

function updateBetStatus(refreshRate) {

    var data = GetXMLData("/XMLData/HTML_RequestList.aspx");
	var divBetStatus = document.getElementById("betstatus");
	if (divBetStatus != null) divBetStatus.innerHTML = data;
	Betslip_CalculateHeight(); Betslip_Resize(); Betslip_ScrollToLatestBet();
	setTimeout("updateBetStatus(refreshRate)", (refreshRate))
}

var refreshRate = 30000;

function Betslip_RepeatSingleStake() {
    var arrSingleSelectionStakeInputs = $("#pre-game-selections input[id*=Stake]");
    var blnRepeatSingleStake = true;
    var intSingleSelectionStakeInputLength = arrSingleSelectionStakeInputs.length;
    var fltRepeatStakeValue = 0;
    
    strFirstValue = arrSingleSelectionStakeInputs[0].value;

    // if the first value is populated then use this value to repeat
    if (strFirstValue != "") {
        fltRepeatStakeValue = strFirstValue;
    }
    else {
        // else need to search for the highest value present in any other stake input box
        arrSingleSelectionStakeInputs.each(function(i) {
            var fltCurrentStakeValue = parseFloat(this.value);
            if (fltCurrentStakeValue > fltRepeatStakeValue) {
                fltRepeatStakeValue = fltCurrentStakeValue;
                blnRepeatSingleStake = true;
            }
        });
    }
    // if we need to repeat the single stake then do so
    if (blnRepeatSingleStake) {
        arrSingleSelectionStakeInputs.each(function(i) {
            this.value = fltRepeatStakeValue;
            this.onkeyup();
        });
    }
}


function Betslip_Init() {
    $(window).resize(function() {
        Betslip_CalculateHeight();
        Betslip_Resize();
    });
    




//    $(window).bind("resize", Betslip_Resize);

    $("#bet-slip-container").bgiframe({ src: "about:blank" });
    $("#bet-slip-header").bind('click', Betslip_Toggle);
    $("#pre-game-selections input[uniqueid]").bind("keyup", StoreUnsavedStakes);
    
    Betslip_ApplyViews();
    Betslip_ApplyTooltips();
    Betslip_ApplyWordWrapping();
}

// populates stakes that have not been saved from the cookie
function Betslip_PopulatePendingStakes() {
    var arrSingleSelectionStakeInputs = $("#pre-game-selections input[uniqueid]");
    var strStakesCookie = $.cookie("IASStakes");
    var arrStakesCookie;

    if ((strStakesCookie != null) && (strStakesCookie != "")) {
        arrStakesCookie = strStakesCookie.split("|");
        $.each(arrStakesCookie,
            function(intIndex, strValue) {
                var arrKeyPair = strValue.split("=");
                if (arrKeyPair.length == 2) {
                    var strId = arrKeyPair[0];
                    var strStake = arrKeyPair[1];
                    eleStakeInput = $("#pre-game-selections input[uniqueid*=" + strId + "]");
                    if (eleStakeInput.length == 1) {
                        eleStakeInput[0].value = strStake;
                        eleStakeInput[0].onkeyup();
                    }
                }
            }
        );
    }
}

function Betslip_ApplyWordWrapping() {
    // firefox does not break words - so need to insert breaks
//    if (navigator.userAgent.indexOf("Firefox")!=-1)
//    {
//        var eleSelections = $("#bet-slip-container .selection-name");
//        var intSelectionsLength = eleSelections.length;
//        debugger;
//        for (var x = 0; x < intSelectionsLength; x++) {
//            var strInnerText = eleSelections[x].textContent;
//            if ((strInnerText != "") && (strInnerText.length > 11)){
//                strInnerText = strInnerText.replace(/<[^>]([\s\S]{11})*>/g, "$1<wbr>");
//                $(eleSelections[x]).html(strInnerText);
//            }
//        }
//    }
}

function Betslip_ApplyViews() {
    Betslip_ApplyMultiView();
    Betslip_ApplyExoticView();
    Betslip_ApplyTeaserView();
}

function Betslip_ApplyMultiView() {
    var strBetslipMultiOpen = "";
    
    strBetslipMultiOpen = $.cookie("IASBetSlipMultiOpen");

    if (strBetslipMultiOpen == "true") {
        $("#pre-game-multiple-bet-options .header").bind('click', Betslip_ToggleMultiOptions).addClass("expanded");
        Betslip_OpenMultiOptions(false);
    }
    else if (strBetslipMultiOpen == "false") {
        $("#pre-game-multiple-bet-options .header").bind('click', Betslip_ToggleMultiOptions).addClass("collapsed");
        Betslip_CloseMultiOptions(false);
    }
    else
    {
        $("#pre-game-multiple-bet-options .header").bind('click', Betslip_ToggleMultiOptions).addClass("expanded");
        Betslip_OpenMultiOptions(false);
    }
}

function Betslip_ApplyExoticView() {
    var strBetslipExoticOpen = "";
    
    strBetslipExoticOpen = $.cookie("IASBetSlipExoticOpen");

    if (strBetslipExoticOpen == "true") {
        $("#pre-game-exotic-bet-options .header").bind('click', Betslip_ToggleExoticOptions).addClass("expanded");
        Betslip_OpenExoticOptions(false);
    }
    else if (strBetslipExoticOpen == "false") {
        $("#pre-game-exotic-bet-options .header").bind('click', Betslip_ToggleExoticOptions).addClass("collapsed");
        Betslip_CloseExoticOptions(false);
    }
    else
    {
       $("#pre-game-exotic-bet-options .header").bind('click', Betslip_ToggleExoticOptions).addClass("expanded");
        Betslip_OpenExoticOptions(false);
    }
}

function Betslip_ApplyTeaserView() {
    var strBetslipTeaserOpen = "";
    
    strBetslipTeaserOpen = $.cookie("IASBetSlipTeaserOpen");

    if (strBetslipTeaserOpen == "true") {
        $("#pre-game-teaser-options .header").bind('click', Betslip_ToggleTeaserOptions).addClass("expanded");
        Betslip_OpenTeaserOptions(false);
    }
    else if (strBetslipTeaserOpen == "false") {
        $("#pre-game-teaser-options .header").bind('click', Betslip_ToggleTeaserOptions).addClass("collapsed");
        Betslip_CloseTeaserOptions(false);
    }
    else
    {
        $("#pre-game-teaser-options .header").bind('click', Betslip_ToggleTeaserOptions).addClass("expanded");
        Betslip_OpenTeaserOptions(false);
    }
}


function Betslip_ApplyTooltips() {
    $("#bet-slip-container [title]*").tooltip({
        showURL: false,
        loadURL: true,
        showBody: " | ",
        extraClass: "custom-tooltip",
        track: true,
        top: 0,
        delay: 1000
    });
}

function Betslip_ToggleMultiOptions() {
    var strBetslipMultiOpen = "";
    
    strBetslipMultiOpen = $.cookie("IASBetSlipMultiOpen");

    if (strBetslipMultiOpen == "true") {
        Betslip_CloseMultiOptions(true);
    }
    else {
        Betslip_OpenMultiOptions(true);
    }
}


function Betslip_ToggleExoticOptions() {
    var strBetslipExoticOpen = "";
    
    strBetslipExoticOpen = $.cookie("IASBetSlipExoticOpen");

    if (strBetslipExoticOpen == "true") {
        Betslip_CloseExoticOptions(true);
    }
    else {
        Betslip_OpenExoticOptions(true);
    }
}

function Betslip_ToggleTeaserOptions() {
    var strBetslipTeaserOpen = "";
    
    strBetslipTeaserOpen = $.cookie("IASBetSlipTeaserOpen");

    if (strBetslipTeaserOpen == "true") {
        Betslip_CloseTeaserOptions(true);
    }
    else {
        Betslip_OpenTeaserOptions(true);
    }
}

function Betslip_CloseMultiOptions(blnSlide) {
    $("#pre-game-multiple-bet-options .header").removeClass("expanded").addClass("collapsed");
    if (blnSlide) {
        $("#pre-game-multiple-bet-options .body").slideUp("fast");
    }
    else {
        $("#pre-game-multiple-bet-options .body").hide();
    }
    
    $.cookie("IASBetSlipMultiOpen", "false");
}

function Betslip_OpenMultiOptions(blnSlide) {
    $("#pre-game-multiple-bet-options .header").removeClass("collapsed").addClass("expanded");
    if (blnSlide) {
        $("#pre-game-multiple-bet-options .body").slideDown("fast", function() { Betslip_CalculateHeight(); Betslip_Resize(); });
    }
    else {
        $("#pre-game-multiple-bet-options .body").show(function() { Betslip_CalculateHeight(); Betslip_Resize(); });
    }
    
    $.cookie("IASBetSlipMultiOpen", "true");
}

function Betslip_CloseExoticOptions(blnSlide) {
    $("#pre-game-exotic-bet-options .header").removeClass("expanded").addClass("collapsed");
    if (blnSlide) {
        $("#pre-game-exotic-bet-options .body").slideUp("fast");
    }
    else {
        $("#pre-game-exotic-bet-options .body").hide();
    }
    
    $.cookie("IASBetSlipExoticOpen", "false");
}

function Betslip_OpenExoticOptions(blnSlide) {
    $("#pre-game-exotic-bet-options .header").removeClass("collapsed").addClass("expanded");
    if (blnSlide) {
        $("#pre-game-exotic-bet-options .body").slideDown("fast", function() { Betslip_CalculateHeight(); Betslip_Resize(); });
    }
    else {
        $("#pre-game-exotic-bet-options .body").show(function() { Betslip_CalculateHeight(); Betslip_Resize(); });
    }
    
    $.cookie("IASBetSlipExoticOpen", "true");
}

function Betslip_CloseTeaserOptions(blnSlide) {
    $("#pre-game-teaser-options .header").removeClass("expanded").addClass("collapsed");
    if (blnSlide) {
        $("#pre-game-teaser-options .body").slideUp("fast");
    }
    else {
        $("#pre-game-teaser-options .body").hide();
    }
    
    $.cookie("IASBetSlipTeaserOpen", "false");
}

function Betslip_OpenTeaserOptions(blnSlide) {
    $("#pre-game-teaser-options .header").removeClass("collapsed").addClass("expanded");
    if (blnSlide) {
        $("#pre-game-teaser-options .body").slideDown("fast", function() { Betslip_CalculateHeight(); Betslip_Resize(); });
    }
    else {
        $("#pre-game-teaser-options .body").show(function() { Betslip_CalculateHeight(); Betslip_Resize(); });
    }
    
    $.cookie("IASBetSlipTeaserOpen", "true");
}

function Betslip_Toggle() {

    var strBetslipOpen = "";

    strBetslipOpen = $.cookie("IASBetSlipOpen");

    if (strBetslipOpen == "true") {
        Betslip_CloseBetslip(true);
    }
    else {
        Betslip_OpenBetslip(true);
    }
}

function Betslip_OpenBetslip(blnSlide) {

    if (blnSlide) {
        $("#bet-slip-body").slideDown(400);
    }
    else {
        $("#bet-slip-body").show();
    }
    
    $("#toggle-bet-slip").removeClass("collapsed");
    $("#toggle-bet-slip").addClass("expanded");

    //expiry value in days, so 0.1 is 2.4 hours.
    $.cookie("IASBetSlipOpen", "true", {expires: 0.1});

    Betslip_CalculateHeight();
    Betslip_Resize();
    Betslip_ScrollToLatestBet();
}

function Betslip_CloseBetslip(blnSlide) {

    if (blnSlide) {
        $("#bet-slip-body").slideUp(400);
    }
    else {
        $("#bet-slip-body").hide();
    }
    
    $("#toggle-bet-slip").removeClass("expanded");
    $("#toggle-bet-slip").addClass("collaped");
    
    $.cookie("IASBetSlipOpen", "false");
}

function anyfunction(params) {
    $("input[id$=NewBet]")[0].value = params;
    $("input[id$=testclick]")[0].click();
}

function Betslip_CalculateHeight() {
    var eleLiveBetContainer = $("#betstatus");
    var eleReceiptContainer = $("#receipt-selections");
    var eleReceiptEmpty = $("#betslip #receipt-empty");
    var eleSingleContainer = $("#pre-game-selections");
    var eleMultiContainer = $("#pre-game-multiple-bet-options");
    var eleTeaserContainer = $("#pre-game-teaser-options");
    var eleExoticContainer = $("#pre-game-exotic-bet-options");
    var intAdditionalFixedHeight = 0;
    
    intBetslipVariableItemHeightTotal = 0;
    intNumberOfDynamicSections = 0;
    
    // determine all the containers that are dynamic (adding fixed height sections where applicable)

    if (eleLiveBetContainer.length != 0) {
        intAdditionalFixedHeight += 56;
        var eleLiveBetNote = $("#live-bet-slip-note");
        intBetslipVariableItemHeightTotal += ParseIntCss("#bsbody .table-container", "height", eleLiveBetContainer[0].offsetHeight);
        intNumberOfDynamicSections++;
        if ((eleLiveBetNote.length != 0) && (eleLiveBetNote.height() > 0))
        {
            intBetslipVariableItemHeightTotal += ParseIntCss("#live-bet-slip-note", eleLiveBetNote[0].offsetHeight);
            intNumberOfDynamicSections++;
        }
    }

    if (eleReceiptContainer.length != 0) {
        if (eleReceiptEmpty.length == 0) {
            intAdditionalFixedHeight += 90;
            intBetslipVariableItemHeightTotal += ParseIntCss("#receipt-selections .table-container", "height", eleReceiptContainer[0].offsetHeight);
            intNumberOfDynamicSections++;
        }
    }
    else {

        if (eleSingleContainer.length != 0) {
            intBetslipVariableItemHeightTotal += ParseIntCss("#pre-game-selections .table-container", "height", eleSingleContainer[0].offsetHeight);
            intNumberOfDynamicSections++;
        }

        if (eleMultiContainer.length != 0) {
            intBetslipVariableItemHeightTotal += ParseIntCss("#pre-game-multiple-bet-options .table-container", "height", eleMultiContainer[0].offsetHeight) + 103;
            intNumberOfDynamicSections++;
        }

        if (eleTeaserContainer.length != 0) {
            intBetslipVariableItemHeightTotal += ParseIntCss("#pre-game-teaser-options .table-container", "height", eleTeaserContainer[0].offsetHeight) + 43;
            intNumberOfDynamicSections++;
        }
        
        if (eleExoticContainer.length != 0) {
            intBetslipVariableItemHeightTotal += ParseIntCss("#pre-game-exotic-bet-options .table-container", "height", eleExoticContainer[0].offsetHeight) + 43;
            intNumberOfDynamicSections++;
        }
    }

    intBetSlipHeight = intBetslipFixedItemHeightTotal + intAdditionalFixedHeight + intBetslipVariableItemHeightTotal;
}

function Betslip_Resize(eventObject) {

    var objTableContainers = $(".table-container");
    var intWindowHeight = $(window).height();
    var intWindowWidth = $(window).width();
    var arrVariableContainerHeights = new Array();
    var intCurrentAvailableHeight = Math.round((intWindowHeight - intBetslipFixedItemHeightTotal));
    var intNewVariableItemHeight = Math.round((intWindowHeight - intBetslipFixedItemHeightTotal) / intNumberOfDynamicSections);
    var intNewHeight;
    var intRemainingDynamicSections = intNumberOfDynamicSections;
    var blnIe6Detected = (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1);
    var eleLiveBetNote = $("#live-bet-slip-note");
    var strFinalVariableHeight;
    
    // if this is IE6 then we will need to adjust the position of the betslip as the screen is resized
    if (blnIe6Detected) {
        $("#bet-slip-container").css("float", "right").css("position", "fixed").css("position", "absolute").css("right", "0px");
        $("#bet-slip-loading").css("float", "right").css("position", "fixed").css("position", "absolute");
    }
    
    // if the betslip is currently showing off the screen
    if (intBetSlipHeight >= intWindowHeight) {



        // loop through each of the dynamic sections
        objTableContainers.each(function(i) {
            var eleThis = $(this);
            var intChildHeight = eleThis.children()[0].offsetHeight;

            intNewHeight = intChildHeight;
            // if the new adjusted variable is bigger than the current container then use the current container
            // height and then reallocate the remaining space amoungst the other variable containers
            
            if (intChildHeight < intNewVariableItemHeight) {
                intNewHeight = intChildHeight;
                intRemainingDynamicSections--;
                intNewVariableItemHeight = Math.round((intWindowHeight - intBetslipFixedItemHeightTotal) / (intRemainingDynamicSections) - intChildHeight);
            }

 
            arrVariableContainerHeights[i] = intNewHeight;
        });

        // loop through each container and set the new variable heights
        objTableContainers.each(function(i) {
            var eleThis = $(this);
            strFinalVariableHeight = intNewVariableItemHeight + "px";
            
            // if the current container is less than the new variable height then use the current containers original height
            if (arrVariableContainerHeights[i] < intNewVariableItemHeight) {
                strFinalVariableHeight = arrVariableContainerHeights[i] + "px";
            }
            eleThis.css("height", strFinalVariableHeight);
        });


        if (($("#betstatus").length != 0) && (eleLiveBetNote.length > 0)) {
            // if the ajusted space is left than the size of the bet note then adjust the size
            if (intNewVariableItemHeight < eleLiveBetNote.height()) {
                eleLiveBetNote.css('height', strFinalVariableHeight);
            }
        }
    }
}

function ParseIntCss(strSelector, strCssAttribute, intDefaultValue) {
    var intValue = parseInt($(strSelector).css(strCssAttribute));
    var intReturnValue = 0;
    if (intDefaultValue) {
        intReturnValue = intDefaultValue;
    }
    
    if (!isNaN(intValue)) {
        intReturnValue = intValue;
    }

    return intReturnValue;
}

function Betslip_Print() {
    if (blnIe6Detected) {
        $("#header").bgiframe({ opacity: false });
        $('#language-selection-menu li ul').bgiframe({ opacity: false });
        $('#account-balance-header ul').bgiframe({ opacity: false });
        $("#bet-slip-container").bgiframe({ opacity: false });
        $("iframe").remove();
    };
    window.print();
}

function GetBetSlipData(url, formName) {
    var frm = document.getElementById(formName);
    frm.action = url;
    frm.target = "betSlipFrame";
    frm.submit();
//    var el = document.createElement("input");
//    el.type = "hidden";
//    el.name = "XMLId";
//    el.value = document.getElementById("XMLId").value;
//    frm.appendChild(el);
    
}
