Array.prototype.exists = function(search){
  for (var i=0; i<this.length; i++)
    if (this[i] == search) return true;	
  return false;
}


$(document).ready(function() {
    if ($("table.dataListing div.lss_selections").length > 1) {
        disableSelection(document.getElementById("VProductsBetControl_lssVproductsStandard"))
        $("input[type='reset']").click(); //this is to reset on page load to cover for browser back and forward.
        $("table.dataListing div.lss_selections:not(div.lss_disabled):not(div.lss_scratched)").livequery("click", function(event) {
            if ("true" == $("input#lss_reserves").val()) {
                var reservesSelected = getReservesSelected($(this));
                if (0 == reservesSelected) {
                    if ($(this).html().indexOf("A") > 0) {
                        $(this).html($(this).html().replace(/A/, ""));
                        $(this).removeClass("lss_ReservedSelected");
                    } else {
                        $(this).html($(this).html() + "A");
                        $(this).addClass("lss_ReservedSelected");
                    }
                } else
                    if (1 == reservesSelected) {
                    if ($(this).html().indexOf("A") > 0) {
                        $(this).html($(this).html().replace(/A/, ""));
                        $(this).removeClass("lss_ReservedSelected");
                    } else
                        if ($(this).html().indexOf("B") > 0) {
                        $(this).html($(this).html().replace(/B/, ""));
                        $(this).removeClass("lss_ReservedSelected");
                    }
                    else {
                        $(this).html($(this).html() + "B");
                        $(this).addClass("lss_ReservedSelected");
                    }
                } else
                    if (2 == reservesSelected) {
                    if ($(this).html().indexOf("A") > 0) {
                        $(this).html($(this).html().replace(/A/, ""));
                        $(this).removeClass("lss_ReservedSelected");
                        if (getReservesSelected($(this)) > 0) {
                            replaceReserveAwithReserveB($(this));
                        }
                    }
                    if ($(this).html().indexOf("B") > 0) {
                        $(this).html($(this).html().replace(/B/, ""));
                        $(this).removeClass("lss_ReservedSelected");
                    }
                }
            } else {
                if ($(this).hasClass("lss_selected")) { $(this).removeClass("lss_selected"); } else { $(this).addClass("lss_selected"); }
                setSelectionsForAllRows();
            }
        });
    }



    // Initialise Code - as form Loaded
    $("input#lss_betCost").val("0.00");
    if ($("#lss_bet-information").length > 0) {
        $("#lss_bet-information>tbody>tr#lss_bet-informationRow>td:nth-child(5)").text($("input#" + ssInputBetBaseUnitCost).val());
    }

    if (getParameter("leg").length > 0) { $("div#lss_race-details").fadeIn(500); }


    //---------- Link Click for "Field" select all starters -
    $("a.lss_field").click(function() {
        if ($(this).hasClass("lss_field_selected")) {
            $(this).parent().parent().children("td").children("div:not(div.scratched)").removeClass("lss_selected");
            $(this).removeClass("lss_field_selected");
            setSelectionsForAllRows();
        } else {
            $(this).addClass("lss_field_selected");
            $(this).parent().parent().children("td").children("div:not(div.lss_scratched)").addClass("lss_selected");
            setSelectionsForAllRows();
        }
    });
    // ------------------------------------------------------


    // This is for handling show/hide race details
    //    $("a.lss_view-race-details").click(function() {
    //        if ("none" == $("div#lss_race-details").css("display")) {
    //            showRaceStarters(this.id);
    //            $("div#lss_race-details").fadeIn(500);
    //            return false;
    //        } else {
    //            if (this.id == $("div#lss_leg-details").find(".raceNumber").text()) {
    //                $("div#lss_race-details").fadeOut(500);
    //            }
    //            else {
    //                $("div#lss_race-details").hide();
    //                showRaceStarters(this.id);
    //                $("div#lss_race-details").fadeIn(500);
    //            }
    //            return false;
    //        }
    //    });
    //    function showRaceStarters(raceNumber) {
    //        var queryStringData = $("table#lss_mainTable").data('data');
    //        queryStringData.pstrRaceNumber = raceNumber;
    //        $("div#lss_race-details").load("/RWWA.TabOzbet.Website/UI/VbetUI/VbetRaceDetails.aspx", queryStringData);
    //    }
    //    $("a.res_view-race-details").click(function() {
    //        if ("none" == $("div#res_race-details").css("display")) {
    //            $("div#res_race-details").fadeIn(500);
    //            return false;
    //        } else {
    //            $("div#res_race-details").fadeOut(500);
    //            return false;
    //        }
    //    });
    //    
    //
    $("a.lss_view-race-details").click(function() {
        if ("none" == $("div#lss_race-details").css("display")) {
            showRaceStarters(this.id);
            $("div#lss_race-details").fadeIn(500);
            return false;
        } else {
            if (this.id == $("div#lss_leg-details").find(".legNumber").text()) {
                $("div#lss_race-details").fadeOut(500);
            }
            else {
                $("div#lss_race-details").hide();
                showRaceStarters(this.id);
                $("div#lss_race-details").fadeIn(500);
            }
            return false;
        }
    });
    function showRaceStarters(legNumber) {

        var queryStringData = $("table#lss_mainTable").data('data');

        __doPostBack(ssUpdatePanelRaceDetails, legNumber); //works
    }
    $("a.res_view-race-details").click(function() {
        if ("none" == $("div#res_race-details").css("display")) {
            $("div#res_race-details").fadeIn(500);
            return false;
        } else {
            $("div#res_race-details").fadeOut(500);
            return false;
        }
    });
    //------------------------------------------

    $("img.lss_mystery-image").click(function() {
        var mysteryEnabledCount = 0;
        $("img.lss_mystery-image").each(function() {
            if ($(this).hasClass("lss_hide")) { mysteryEnabledCount++; }
        });
        if (0 == mysteryEnabledCount) {
            if (confirm("As a result of enabling mystery selections on this leg, the following will occur: \r\n\r\n - The bet multiplier will be locked at 1x \r\n - Any reserves you have selected will be removed. \r\n\r\nWould you like to continue?")) {
                $(this).addClass("lss_hide").next().removeClass("lss_hide");
                return;
            }
        } else {
            $(this).addClass("lss_hide").next().removeClass("lss_hide");
        }
    });

    $(".lss_tabs div:not(.lss_active)").hover(function() {
        $(this).addClass("lss_hover");
    }, function() {
        $(this).removeClass("lss_hover");
    });

    $("div#lss_mystery").click(function() {
        if ($("input#lss_combinations").val() > 0) {
            if (confirm("You have clicked the mystery bet button. When you are taken to the mystery bet page any selections you have made here will be lost. \r\n\r\nWould you like to continue?")) {
                document.location = ssMysteryURLLocation;
            }
        }
        else { document.location = ssMysteryURLLocation; }
    });

    $("div#lss_reserver").click(function() {
        if (!$(this).hasClass("lss_disabled")) {
            if (!$(this).hasClass("lss_selected")) {
                $(this).addClass("lss_selected");
                $("input#lss_reserves").val("true");
            } else {
                $(this).removeClass("lss_selected");
                $("input#lss_reserves").val("false");
            }
        }
    });

    $("input[type='reset']").click(function() {
        $("div.lss_selections").each(function() {
            $(this).removeClass("lss_selected");
            $(this).removeClass("lss_ReservedSelected");
            $(this).html($(this).html().replace(/A|B/, ""));
        });
        $("span.lss_selection-count").text("0");
        $("a.lss_field").removeClass("lss_field_selected");
        $("input#txtMultiplier").val(1);
        setCombinationCount();
    });


    $("#txtMultiplier").keydown(function(event) {
        var charCode = (navigator.appName == "Netscape") ? event.which : event.keyCode;
        if ((charCode == 0) ||
        (charCode == 8) ||
        (charCode == 10) ||
        (charCode == 13) ||
        (charCode == 37) ||
        (charCode == 39) ||
        (charCode == 46) ||
        (charCode >= 48 && charCode <= 57) ||
        (charCode >= 95 && charCode <= 106)
        ) {
            return true;
        }
        else {
            return false;
        }
    });
    $("#txtMultiplier").keyup(function(event) { setBetCost(); });

    if ("true" == $("input#VProductsBetControl_hiddenBettingDisabled").val()) {
        disableBetting();
    }
});


function setCombinationCount(){
	var combinations = 0;
	var hasEmptyRow = false;
	$("span.lss_selection-count").each(function(i){
		if('0'==$(this).text()){hasEmptyRow = true;}
		if(0==combinations){
			combinations = $(this).text();
		}else{
			combinations = combinations * $(this).text();
		}
	});
	if(hasEmptyRow){
		$("input#lss_combinations").val("0");
	}else{
		$("div#errDiv").hide(500);
		$("input#lss_combinations").val(combinations);
	}
	setBetCost();
}

function setBetCost() {
    var baseUnit = $("input#" + ssInputBetBaseUnitCost).val();
    var betCost = $("input#lss_combinations").val() * $("input#txtMultiplier").val() * baseUnit;
	betCost = betCost.toFixed(2);
	$("input#lss_betCost").val( betCost );
}

function setSelectionsForAllRows(){
    $("div#VProductsBetControl_lssVproductsStandard table#raceListDataGrid tr").each(function(i) {
		$(this).children().children("span.lss_selection-count").text($(this).children().children("div.lss_selected").length);
	});
	setCombinationCount();
}

function setSelectionsForRow(selectionDiv){
	var selections = 0;
	selectionDiv.siblings().andSelf().each(function(i){
		if($(this).hasClass("lss_selected")){
			selections++;
		}
	});
	selectionDiv.parent().parent().children().children("span.lss_selection-count").text(selections);
}

function getReservesSelected(div){
	var reservesSelected = 0;
	div.parent().children("div.lss_selections:not(div.lss_disabled):not(div.lss_scratched)").each(function(){
		if(($(this).html().indexOf("A")>0)||($(this).html().indexOf("B")>0)){reservesSelected++;}		
	}); 
	return reservesSelected;
}

function replaceReserveAwithReserveB(div){
	div.parent().children("div.lss_selections:not(div.lss_disabled):not(div.lss_scratched)").each(function(){
		if($(this).html().indexOf("B")>0){$(this).html( $(this).html().replace(/B/,"A") );}
	}); 
}

//----------------------------------------------------------------------------
function removeReserves(){
	$("table.dataListing div.lss_selections:not(div.lss_disabled):not(div.lss_scratched)").each(function(i){
		if($(this).html().indexOf("A")>0){$(this).html($(this).html().replace(/A/,""));}
		if($(this).html().indexOf("B")>0){$(this).html($(this).html().replace(/B/,""));}
	});
}

//----------------------------------------------------------------------------
function vbetPlaceBet(controlName) {
    if ($("input#lss_combinations").val() > 0) {
        generatePostData();
        getHTML();
        DisableControl($("input[name='" + controlName + "']").get(0));
        submitBet(controlName, '');
        return false;
    } else {
        $("div#errDiv").show(500).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200);
        return false;
    }
}

function getHTML() {
    $("input#" + ssHTMLofBetSelection).val(document.getElementById("raceListDataGrid").outerHTML);
}

//----------------------------------------------------------------------------   
function generatePostData(){
	var betString = '';

	$("table.dataListing tr.lss_selection-row").each(function(i){
		var selectionText = '';
		var reserveTextA = '';
		var reserveTextB = '';
		betString += '..';
		$(this).children().children("td div.lss_selections").each(function(ii){
			$(this).filter(".lss_selected").each(function(ii){
				if(''==selectionText){
					selectionText += $(this).html().replace(/A|B/,"");
				}else{
					selectionText += '.' + $(this).html().replace(/A|B/,"");
				}
			});
		});
		$(this).children().children("td div.lss_selections").each(function(ii){
			if($(this).html().indexOf("A")>0){
				reserveTextA += '.X' + $(this).html().replace(/A/,"");
			}
			if($(this).html().indexOf("B")>0){
			    reserveTextB += '.X' + $(this).html().replace(/B/, "");
			}
		});
		betString += selectionText + reserveTextA + reserveTextB;
	});
	var betCost = Math.round($("input#lss_betCost").val() * 100);
	betString += '..' + betCost;
	$("input#" + ssInputBetSelection).val(betString);
}

//----------------------------------------------------------------------------
function populateLottoPageFromBetString(betString){
	try{
		var reserveTextA = '';
		var reserveTextB = '';

		myregexp = new RegExp(/(V\d+)T/);
		mymatch = myregexp.exec(betString);
		betString += $("input#bet-type").val(mymatch[1]);

		myregexp = new RegExp(/(T\d+)P/);
		mymatch = myregexp.exec(betString);
		betString += $("input#track-code").val(mymatch[1]);

		myregexp = new RegExp(/(P\d+)\.\./);
		mymatch = myregexp.exec(betString);
		betString += $("input#program-number").val(mymatch[1]);

		legs = betString.split("..");

		$("table.dataListing tr.lss_selection-row").each(function(i){
			selections = legs[i+1].split(".");
			var reserves = new Array();
			for(iii=1;iii<selections.length;iii++){			
				if( selections[iii].indexOf("X")>-1 ){
					reserves.push(selections[iii]);
				}
			} iii=0;

			$(this).children().children("td div.lss_selections").each(function(ii){
				if(selections.exists(ii+1)){
					$(this).addClass("lss_selected");
				}
				if(selections.exists("X"+(ii+1))){
					if(reserves[0]=="X"+(ii+1)){
						$(this).html($(this).html()+"A");
					} else {
						$(this).html($(this).html()+"B");
					}
				}
			});
		});

		setSelectionsForAllRows();
		setCombinationCount();
		totalBetValue = legs[legs.length-1];

		myregexp = new RegExp(/^(\d+)/);
		mymatch = myregexp.exec(totalBetValue);
		totalBetValue = mymatch[1];

		betCost = $("input#lss_betCost").val() * 100;

		multiplierValue = totalBetValue / betCost;

		//$("select#lss_multiplier").val(multiplierValue);
		$("inputt#txtMultiplier").val(multiplierValue);
		finalBestCost = ( multiplierValue * betCost ) / 100;

		$("input#lss_betCost").val( finalBestCost.toFixed( 2 ) ); 
	} catch(err) {
		alert("Error: Invalid Bet String");
	}
}

//----------------------------------------------------------------------------
//Remove this function for qual/prod. Used to simulate action based on querystring parameters.
function getParameter(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results==null)
    return "";
  else
    return results[1];
}

//----------------------------------------------------------------------------
function disableSelection(target){
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false}
	target.style.cursor = "default"
}

//----------------------------------------------------------------------------
function disableBetting() {
    $("table.dataListing div.lss_selections").addClass("lss_scratched");
    $("a.lss_field").parent().html("field");
    $("input#lss_combinations,input#txtMultiplier,input#lss_unit,input#lss_betCost").attr("disabled", "disabled");
    $("div#lss_reserver").unbind("click").css("cursor", "default").css("color", "#999999");
    $("input[type='reset']").unbind("click").attr("disabled", "disabled");
    $("input#lss_submit").unbind("click").attr("disabled", "disabled");
    $("input[type='submit']").unbind("click").attr("disabled", "disabled");
    $("div#lss_mystery").unbind("click").css("cursor", "default").css("color", "#999999");   
}

//----------------------------------------------------------------------------
function jumpToURL(oldDay, oldMonth, oldYear) {
    document.forms[0].submit();
}

