﻿function TJKHelper(oyuntip, choices, maxcolumns) {
    var retval = 0;

    $.ajax({
        type: "POST",
        url: "/Default.aspx/CalculateCoupon",
        data: "{coupontype: " + oyuntip + ", choices: '" + choices + "', maxcolumns: " + maxcolumns + " }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(msg) {
            retval = msg.d;
        }
    });

    return retval;
}

function PlayHorseRaceCoupon(save, bonus) {
    $('#hdnPlay').val("1");
    document.getElementById("btnHemenOyna").style.visibility = "hidden";
    $.ajax({
        type: "POST",
        url: "/Default.aspx/PlayHorseRaceCoupon",
        data: "{savecoupon: " + save + ", bonus : " + bonus + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function(msg) {
            if (msg.d.split("[ERROR]").length > 1) {//(msg.d == "") {
                $('#hdnPlay').val("0");
                document.getElementById("btnHemenOyna").style.visibility = "visible";
                modalWarning(msg.d.split("[ERROR]")[1]);
            }
            else {
                //modalSuccess('Kupon Oynandı.');
                $('#divCoupon').html(msg.d);
            }
        },
        error: function(xmlHttpRequest, status, err) {
            $('#hdnPlay').val("0");
            document.getElementById("btnHemenOyna").style.visibility = "visible";
            modalWarning('Kupon Yüklenemedi.');
        }
    });
}

function GetCoupon(programid, raceno, gametype, multiply, tr_gametype) {

    $.ajax({
        type: "POST",
        url: "/Default.aspx/GetCoupon",
        data: "{programid: " + programid + ",raceno: '" + raceno + "',gametype: " + gametype + ",multiply: " + multiply + ",tr_gametype: '" + tr_gametype + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        async: false,
        success: function(msg) {
            if (msg.d.split("[ERROR]").length > 1) {
                //GetCoupon(0, 0, 0, 0, '');
                //GetCouponError('Bir Hata Oluştu');
                modalWarning('Oynamak istediğiniz Bahis Kapandığından Kuponunuz Silinmiştir.');
                setTimeout("ErrorRedirect() ", 2000);
            }
            else {
                $('#divCoupon').html(msg.d);
            }
        },
        error: function(xmlHttpRequest, status, err) {
            modalWarning('Kupon Yüklenemedi.');
            alert("hata");
        }
    });

    if (programid == 0) {
        var TJKorgIframe = getQueryVariableTJK("TJK");
        if (TJKorgIframe != undefined && TJKorgIframe == "1") {
            var link = document.location.href;
            GoHRMenu(link.split("?")[0]);
        }
    }
}

function ClearHorseRaceCoupon(type) {
    if (type == 'ganyan') {
        $('input[name="cb_ganyan"]:checked').each(function(index) {
            id = $(this).attr("id");
            document.getElementById(id).checked = false;
        });
        calculate(gametype, 'ganyan', '');
    }
    else {
        document.getElementById("ddl_1").selectedIndex = 0;
        secildi(1);
    }

}

function getQueryVariableTJK(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
}

function GetChoices() {
    $.ajax({
        type: "POST",
        url: "/Default.aspx/GetChoices",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        async: false,
        success: function(msg) {
            document.getElementById("TJKorgIframe").value = msg.d;
        },
        error: function(xmlHttpRequest, status, err) {
            modalWarning('Kupon İçeriği Yüklenemedi.');
        }
    });
}

function GetConfirm(programid, gameid, raceno, multiply, betcount, price, choices, tr_gametype, cb) {

    var PredefinedCouponId = 0;

    if (document.getElementById("PredefinedCouponId") != undefined) {
        PredefinedCouponId = document.getElementById("PredefinedCouponId").value;
    }

    $.ajax({
        type: "POST",
        url: "/Default.aspx/GetConfirm",
        data: "{programid: " + programid + ",gameid: " + gameid + ",raceno: '" + raceno + "',multiply: " + multiply + ",betcount: " + betcount + ",price: '" + price + "',choices: '" + choices + "',tr_gametype: '" + tr_gametype + "',cb: '" + cb + "',predefinedcouponid: " + PredefinedCouponId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function(msg) {
            if (msg.d.split("[ERROR]").length > 1) {
                //GetCoupon(0, 0, 0, 0, '');
                //GetCouponError('Bir Hata Oluştu');
                modalWarning('Oynamak istediğiniz Bahis Kapandığından Kuponunuz Silinmiştir.');
                setTimeout("ErrorRedirect() ", 2000);
            }
            else {
                if (msg.d != "") {
                    $('#divCoupon').html(msg.d);
                }
                else {
                    var TJKorgIframe = getQueryVariableTJK("TJK");
                    if (TJKorgIframe != undefined && TJKorgIframe == "1") {
                        var link = document.location.href.split("?")[0];
                        GoHRMenu(link, true);
                        //modalWarning('<center>Kupon Oynamak İçin Önce Üye Girişi Yapmalısınız.<p>Üye girişi yapmak için lütfen <a href="' + link + '" target="_blank">tıklayınız</a></center>');
                    }
                    else {
                        modalWarning('Lütfen Önce Üye Girişi Yapınız.');
                    }
                }
            }
        },
        error: function(xmlHttpRequest, status, err) {
            modalWarning('Kupon Yüklenemedi.');
        }
    });
}

{


    function GetHRMenu(programid, gameid, raceno, multiply, betcount, price, choices, choices_, tr_gametype, cb) {


        if (cb == undefined) {
            cb = "";
        }

        
        $.ajax({
            type: "POST",
            url: "/Default.aspx/GetHRMenu",
            data: "{programid: " + programid + ",gameid: " + gameid + ",raceno: '" + raceno + "',multiply: " + multiply + ",betcount: " + betcount + ",price: '" + price + "',choices: '" + choices + "',choices_: '" + choices_ + "',tr_gametype: '" + tr_gametype + "',cb: '" + cb + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            async: false,
            success: function(msg) {
                //                    if (msg.d != "") {
                //                        $('#divCoupon').html(msg.d);
                //                    }
                //                    else {
                //                        modalWarning('Lütfen Önce Üye Girişi Yapınız.');
                //                    }
            },
            error: function(xmlHttpRequest, status, err) {
                //                    modalWarning('Kupon Yüklenemedi.');
            }
        });
    }

    function GetCouponError(errormessage) {
        $.ajax({
            type: "POST",
            url: "/Default.aspx/GetCouponError",
            data: "{errormessage: '" + errormessage + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function(msg) {
//                if (msg.d.split("[ERROR]").length > 1) {
//                    GetCoupon(0, 0, 0, 0, '');
//                }
//                else {
                    $('#divCoupon').html(msg.d);
//                }
            },
            error: function(xmlHttpRequest, status, err) {
                modalWarning('Kupon Yüklenemedi.');
            }
        });
    }

    function ErrorRedirect() {
        var fulladress=document.location.href;

        var adress = fulladress.split(".aspx")[0];
        window.location = adress + ".aspx";
    }
    
    function calculate(type, gametype, action) {

        //    if (type == 25) {
        //        type = 9;
        //    }
        //    else if (type == 23) {
        //        type = 12;
        //    }
        //    else if (type == 24) {
        //        type = 14;
        //    }

        var choices = "";
        var choices_ = "";
        var columnprice = $('#hdn_columnprice').val();
        var racecount = $('#hdnracecount').val();

        $('a[name="a_ganyan"]').each(function(index) {
            switch (parseInt(type)) {
                case 1:
                case 2:
                case 3:
                case 5:
                case 7:
                case 10:
                case 15:
                case 16:
                case 17:
                case 18:
                case 19:
                case 26:
                    $(this).html("<img src=\"images/bullets/bltOran2.gif\" title=\"Kupona ekle\">");
                    break;
                default:
                    $(this).html(" ");
                    $(this).attr("onclick", "");
                    break;
            }
        });

        if (gametype == "ganyan") {
            var selectedcboxes = new Array();

            var legs = new Array();
            $('input[name="cb_ganyan"]:checked').each(function(index) {
                id = $(this).attr("id");
                splitted = id.split("_");
                selectedcboxes.push(splitted[1] + "-" + splitted[2]);
                if (!Array.contains(legs, splitted[1]))
                    legs.push(splitted[1]);

                if (id.indexOf('S') > -1) {
                    var index = id.split('_')[1];
                    var tdSystem = document.getElementById("td_System_" + index);
                    var system = document.getElementById("sytem_" + index);
                    tdSystem.style.backgroundImage = "url(../../images/backgrounds/bgSystem.jpg)";
                    system.style.fontSize = "12px";
                    system.style.color = "#FFFFFF";
                }
            });

            selectedcboxes.sort();

            lastleg = 0;
            lastleg_ = 1;
            for (var i = 0; i < selectedcboxes.length; i++) {
                items = selectedcboxes[i];

                leg = items.split("-");

                a = $('#a_' + leg[0] + '_' + leg[1])
                if (a.html() != " ") {
                    a.html("<img src=\"images/bullets/bltOran2sec.gif\" title=\"Kupondan çıkar\">");
                }

                if (lastleg != leg[0] && lastleg != 0) {
                    choices += "|";
                }
                else if (lastleg == leg[0]) {
                    choices += ",";
                    choices_ += ",";
                }

                if (lastleg_ != leg[0]) {
                    for (var i_ = lastleg_; i_ < leg[0]; i_++) {
                        choices_ += "|";
                    }
                    lastleg_ = leg[0];
                }

                choices += leg[1];
                choices_ += leg[1];
                lastleg = leg[0];
            }

            if (lastleg_ != racecount) {
                for (var i_ = lastleg_; i_ < racecount; i_++) {
                    choices_ += "|";
                }
                lastleg_ = racecount
            }
        }
        else if (gametype == "virgullu") {
            var columncount = $('#hdn_columncount').val();
            var secilenler = refresh_selects();
            choices = secilenler.toString();
            choices_ = secilenler.toString();
        }

        document.getElementById("hdn_tjkcouponchoices").value = choices_;
        var tjkChoicesBarContainer = $('#tjk-choices-bar-container');
        if (tjkChoicesBarContainer) {
            if (tjkChoicesBarContainer.css("display") != "none") {
                GetTjkCouponChoicesFromPage();
            }
        }

        if (!tjkOnLoad)
            tjkOnLoad = true;

        var hdnCouponMasterGameType = document.getElementById("ctl00_center_CouponMaster_hdnGameType");
        if (hdnCouponMasterGameType == null)
            hdnCouponMasterGameType = document.getElementById("ctl00_hdnGameType");

        if (gametype == "ganyan") {
            if (choices.split('|').length != parseInt(racecount)) {
                //horsecount = $('#<%= ddlRaces.ClientID %>').val();

                spl = horsecount.split('|');
                if (spl.length > 1) {
                    if (choices.split('|').length != spl[1]) {
                        $('#bet_count').val(0);
                        $('#price').val("0.00");

                        if (action != undefined) {
                            if (action == "submit") { alert("Bütün kolonları doldurmalısınız!"); }
                        }
                        if (action == undefined || (action != undefined && action != "menu")) {
                            if (hdnCouponMasterGameType) {
                                setTJKCouponInfos(choices_, hdnCouponMasterGameType.value, $('#bet_count').val(), $('#ddl_multiple_' + gametype).val());
                            }
                            return;
                        }
                    }
                }
            }
        }


        var cbMultiple = document.getElementById("cb_multiple");
        if (cbMultiple && cbMultiple.checked) {
            type = $('#hdn_gametype').val();
        }

        minprice = $('#hdn_minprice').val();
        maxprice = $('#hdn_maxprice').val();
        maxcols = parseInt(parseFloat(maxprice) / parseFloat(columnprice));

        retv = TJKHelper(parseInt(type), choices, maxcols);
        $('#bet_count').val(retv);

        totalprice = parseFloat(retv) * parseFloat(columnprice);
        totalprice = totalprice.toFixed(2);

        if (choices.indexOf("S") > -1) {
            price = parseFloat($('#ddl_multiple_' + gametype).val()).toFixed(2);
        }
        else {
            price = (totalprice * parseFloat($('#ddl_multiple_' + gametype).val())).toFixed(2);
        }

        if (parseFloat(price) > maxprice && action != "menu") {
            $('#bet_count').val("0.00");
            $('#price').val("0.00");

            if (hdnCouponMasterGameType) {
                setTJKCouponInfos(choices_, hdnCouponMasterGameType.value, $('#bet_count').val(), $('#ddl_multiple_' + gametype).val());
            }

            alert("Maksimum Bahis Tutarı " + parseFloat(maxprice).toFixed(2) + " TL üstü olamaz.\nLütfen Seçim Sayınızı Azaltın.");
            return;
        }

        $('#price').val(price);
        
        if (hdnCouponMasterGameType) {
            setTJKCouponInfos(choices_, hdnCouponMasterGameType.value, $('#bet_count').val(), $('#ddl_multiple_' + gametype).val());
        }
        if (action != undefined) {
            if (action == "submit") {
                if (parseFloat(price) < parseFloat(minprice)) {
                    alert("En az " + parseFloat(minprice).toFixed(2) + " TL'lik kupon yapabilirsiniz!");
                    return;
                }
                else {
                    if (parseFloat(maxprice) > 0) {
                        if (parseFloat(price) > parseFloat(maxprice)) {
                            alert("En fazla " + parseFloat(maxprice).toFixed(2) + " TL'lik kupon yapabilirsiniz!");
                            return;
                        }
                    }
                }

             
                GetConfirm($('#ProgramId').val(),
                                $('#hdn_gametype').val(),
                                $('#RaceNo').val(),
                                $('#ddl_multiple_' + gametype).val(),
                                $('#bet_count').val(),
                                $('#price').val(),
                                choices,
                                $('#tr_GameType').val(),
                               cbMultiple == null ? "" : cbMultiple.checked);
            }

            if (action == "menu") {
                GetHRMenu($('#ProgramId').val(),
                                $('#hdn_gametype').val(),
                                $('#RaceNo').val(),
                                $('#ddl_multiple_' + gametype).val(),
                                $('#bet_count').val(),
                                $('#price').val(),
                                choices,
                                choices_,
                                $('#tr_GameType').val(),
                                cbMultiple == null ? "" : cbMultiple.checked);
            }
        }

        if (document.getElementById("price") != undefined && document.getElementById("price").value == "NaN") {
            GetCoupon(0, '0', 0, 0, '');
        }

        if (document.getElementById("hdn_columnprice").value == "0") {
            GetCoupon(0, '0', 0, 0, '');
        }
    }
}


