// ------------------------------ simple actions ------------------------------

var tonybetActions = {};
tonybetActions.jq= jQuery.noConflict();

(function($) {
    tonybetActions.jq(document).ready(function() {

        // vars
        var sportMenu = $('#bettingCategoriesList');
        var eventsBlock = '';
        var systemTabNumber=2;

        var cookieOptions = {
            path: '/',
            expires: 10
        };

        // gmap
        if (window.googleMapInitialize){
            googleMapInitialize();
        }

        $('.mapItem').click(function() {
            googleMapInitialize();
        });

        if ( $('#bettingCategoriesForm .expanded').length ) {
            $('.showClear').show('slow');
        }

        // actions
        CountTotalStake();
        CountTotalOdds();
        CountTotalWinSimple();
        CountTotalWinMulti();
        CountTotalWinSystem();
        $('.myBid input').blur(myBidInputBlur);
        $('#myBid input').rval('');
        $('.myBid input').rval('');
        $('#mySystemBid input').rval('');
        $('#myBid input').blur(myBidInputBlur);
        $('#mySystemBid input').blur(myBidInputBlur);
        $('.removeBet').click(removeBetClick);
        $('#logOut').click(logOutClick);
        $('#playerProfile form').submit(profileDataFormSubmit);

        // fixes for IE6 widget showing
        function isIE6(){
            return /msie|MSIE 6/.test(navigator.userAgent);
        }
        function refreshTabsIE6(){
            var x = document.getElementById('singlebet');
            var y = document.getElementById('multibet');
            var z = document.getElementById('systembet');
            x.style.display='none';
            x.style.display='block';
            y.style.display='none';
            y.style.display='block';
            z.style.display='none';
            z.style.display='block';
        }

        $('#systembet .betSystemCombinations input[name=system_combination]').live('change',myBidInputBlur);
        $("#myBetsBlockTabs").tabs({
            select: function(event, ui) {
                return CheckBetBlockCount(ui.index);
            },
            show: function(event, ui) {
                if (isIE6()) {
                    setTimeout(refreshTabsIE6, 10);
                }
            }
        });

        $("#betshopsBlockTabs").tabs();
        $("#featuredBetsTabs").tabs();

        $("#homeBetTabs").tabs({
            show: function(event, ui) {
                showEventsHomeBlock(ui);
            }
        });

        $("#playerProfileTabs").tabs( {

            show: function(event, ui) {

                showPlayerProfileBlock(ui);
            }
        }
        );

        $("#ajaxLoadingBlock").ajaxStart(function(){
            $(this).show('fast');
        });
        $("#ajaxLoadingBlock").ajaxStop(function(){
            $(this).hide('fast');
        });

        $('.eventAddBet').click(eventAddBetClick);

        $('.sportLabel').children('input[type=checkbox]').click(function() {
            var sportLabel = $(this);
            sportLabel.parent().parent().find('input[type=checkbox]').each(
                function() {
                    $(this).attr('checked', sportLabel.attr('checked'));
                }
                );

            SetSportMenuClasses();
        });

        $('.countryLabel').children('input[type=checkbox]').click(function() {
            var sportLabel = $(this);
            sportLabel.parent().parent().find('input[type=checkbox]').each(
                function() {
                    $(this).attr('checked', sportLabel.attr('checked'));
                }
                );

            SetSportMenuClasses();
        });

        $('.tournamentLabel').children('input[type=checkbox]').click(function() {
            var tournamentLabel = $(this);
            //alert(tournamentLabel.parent().parent().parent().parent().children('label').html());
            tournamentLabel.parent().parent().parent().parent().children('label').find('input[type=checkbox]').each(
                function() {
                    $(this).attr('checked', false);
                }
                );

            SetSportMenuClasses();
        });

        sportMenu.children('li.expanded').children('ul').find('input[type=checkbox]').click(function() {
            if ($(this).attr('checked')){
                $(this).parent().parent().addClass('selected');
            } else {
                $(this).parent().parent().removeClass('selected');
            }
        });

        $('.showEvents').click(function() {
            showEvents();
        });

        $('.clearEvents').click(function() {
            sportMenu.find('input[type=checkbox]').each(function() {
                $(this).attr('checked', false);
                $(this).parent().parent().removeClass('selected');
            });
        });

        $('.goLink').click(function() {
            $('#bettingCategoriesList').find('input[type=checkbox]').attr('checked', false);
            $('#bettingCategoriesList').find('li').removeClass('selected');


            $(this).parent().addClass('selected');
            $(this).parent().children('label').find('input[type=checkbox]').attr('checked', true);

            showEvents();
        });

        $('#myBetsBlock form').submit(function() {
            myBidInputBlur();
            return false;
        });

        $('#myBetsBlock .submitMyBid input').click(submitMyBidInputClick);

        $('.subBetsList').click(subBetsListClick);
        $('#checkByBarcode').click(checkByBarcode);


        $('#loginForm').submit(function() {
            $.ajax({
                type: "POST",
                url: player_login_url+'?activeLanguage='+active_language,
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data) {
                    if (data.error === false) {
                        $('.userLogIn').html(data.html);
                        showSplash();
                        $('#logOut').click(logOutClick);
                    } else {
                        _alert(data.errorMessage);
                    }
                }
            });

            return false;
        });

        // functions

        function GetBlockBetsCount(obj){
            var betCounter=0;
            obj.find('input.publicnumber').each(function() {
                betCounter++;
            });
            return betCounter;
        }

        function CheckBetBlockCount(tab){
             if(tab==systemTabNumber){
                var systemOverall=GetBlockBetsCount($('#systembet'));
                if(parseInt(systemOverall)>2){
                    $('#myBetsBlockTabs a[href=#systembet] span').removeAttr('class');
                    return true;
                }else{
                    $('#myBetsBlockTabs a[href=#systembet] span').attr('class','disabled');
                    return false;
                }
            }
        }


        function UpdateSession(){

            var selectedTab =  $("#myBetsBlockTabs").tabs('option', 'selected');

                var selectedSystem =  parseInt($("#systembet .betSystemCombinations [name=system_combination]:checked").val())?$("#systembet .betSystemCombinations [name=system_combination]:checked").val():2;

                $.ajax({
                    type: "POST",
                    url: bets_url,
                    async: false,
                    data: {
                        betOperation: 'update',
                        activeLanguage : active_language,
                        cookieNameSingleBet: $.session(cookieNameSingleBet),
                        cookieNameMultiBetStake: $.session(cookieNameMultiBetStake),
                        cookieNameSystemBetStake: $.session(cookieNameSystemBetStake),
                        cookieNameSystemBetInfo: $.session(cookieNameSystemBetInfo)

                    },
                    dataType: 'json',
                    success: function(data) {
                        if (data.error === false) {

                            CheckBetBlockCount(systemTabNumber);
                            $('.betSystemCombinations').html(data.htmlSystemCombinations);
                            CountTotalWinSystem();
                        } else {
                            _alert(data.errorMessage);
                        }
                    }
                });
        }


        function RemoveAllAlreadyBetEvents(){
            $('#eventsBlock').find('input.publicnumber').each(function() {
                var obj = $(this).parent().find('input.oddkey');

                if (obj.length) {
                    obj.parent().parent().removeClass('alreadyBet');
                }
            });
        }

        function SetSportMenuClasses() {
            sportMenu.children('li.expanded').children('ul').find('input[type=checkbox]').each(function() {
                if ($(this).attr('checked')){
                    $(this).parent().parent().addClass('selected');
                } else {
                    $(this).parent().parent().removeClass('selected');
                }
            });
        }

        function eventAddBetClick() {
            var publicnumber = $(this).parent().children('.publicnumber').val();
            var oddkey = $(this).parent().children('.oddkey').val();
            var oddvalue = $(this).parent().children('.oddvalue').val();
            var oddaddvalue = $(this).parent().children('.oddaddvalue').val();
            var prefix = $(this).parent().children('.prefix').val();
            var postfix = $(this).parent().children('.postfix').val();
            var parentBlock = $(this).parent().parent();

            var selectedTab =  $("#myBetsBlockTabs").tabs('option', 'selected');
            var selectedSystem =  parseInt($("#systembet .betSystemCombinations [name=system_combination]:checked").val())?$("#systembet .betSystemCombinations [name=system_combination]:checked").val():0;


            if (!FindBetInSelectedTab(selectedTab, publicnumber, oddkey) && !$('#myBetsBlockTabs .back').length) {
                $.ajax({
                    type: "POST",
                    url: bets_url,
                    data: {
                        publicnumber: publicnumber,
                        oddkey: oddkey,
                        oddvalue: oddvalue,
                        oddaddvalue: oddaddvalue,
                        prefix: prefix,
                        postfix: postfix,
                        activeLanguage : active_language,
                        betOperation: 'add',
                        selectedSystem:selectedSystem
                    },
                    dataType: 'json',
                    success: function(data) {
                        if (data.error === false) {

                            $('#mySingleBets').append(data.htmlSingle);
                            $('#myMultiBets').append(data.htmlMulti);
                            $('#mySystemBets').append(data.htmlMulti);
                            CheckBetBlockCount(systemTabNumber);
                            $('.betSystemCombinations').html(data.htmlSystemCombinations);

                            var selectedTab =  $("#myBetsBlockTabs").tabs('option', 'selected');
                            if( !(CheckBetBlockCount(systemTabNumber)) && selectedTab==systemTabNumber){
                                $("#myBetsBlockTabs").tabs('select', 0);
                            }
                            $('.myBid input').rval('');
                            $('.myBid input').blur(myBidInputBlur);

                            $('.removeBet').click(removeBetClick);
                            parentBlock.addClass('alreadyBet');

                            myBidInputBlur();
                        } else {
                            _alert(data.errorMessage);
                        }
                    }
                });
            }
        }

        function removeBetByPublicNumber( blockObj, publicnumber, oddkey ){

            blockObj.find('input[value="' + publicnumber + '"]').each(function() {
                var obj = $(this).parent().find('input[value="' + oddkey + '"]');

                if (obj.length) {
                    var parentBlock = $(this).parent().parent();
                    parentBlock.remove();
                }
            });



        }

        function removeBetClick() {

            var hasBet = false;
            var publicnumber = $(this).parent().children('.publicnumber').val();
            var oddkey = $(this).parent().children('.oddkey').val();
            var selectedTab =  $("#myBetsBlockTabs").tabs('option', 'selected');
            var parentBlock = $(this).parent().parent();
            parentBlock.remove();

            switch (selectedTab) {
                case 0:
                    removeBetByPublicNumber( $('#myMultiBets'), publicnumber, oddkey);
                    removeBetByPublicNumber( $('#mySystemBets'), publicnumber, oddkey);
                    CheckBetBlockCount(systemTabNumber);
                break;
                case 1:
                    removeBetByPublicNumber( $('#mySingleBets'), publicnumber, oddkey);
                    removeBetByPublicNumber( $('#mySystemBets'), publicnumber, oddkey);
                    CheckBetBlockCount(systemTabNumber);
                break;
                case 2:
                    removeBetByPublicNumber( $('#mySingleBets'), publicnumber, oddkey);
                    removeBetByPublicNumber( $('#myMultiBets'), publicnumber, oddkey);
                    if( !(CheckBetBlockCount(systemTabNumber)) && selectedTab==systemTabNumber){
                        $("#myBetsBlockTabs").tabs('select', 0);
                    }
                break;
            }

            if (selectedTab == 0) {
                hasBet = FindBetInSelectedTab(1, publicnumber, oddkey);
            } else if (selectedTab == 1) {
                hasBet = FindBetInSelectedTab(0, publicnumber, oddkey);
            }

            if (!hasBet){
                $('#eventsBlock').find('input[value="' + publicnumber + '"]').each(function() {
                    var obj = $(this).parent().find('input[value="' + oddkey + '"]');

                    if (obj.length) {
                        obj.parent().parent().removeClass('alreadyBet');
                    }
                });
                $('#homeBetTabs').find('input[value="' + publicnumber + '"]').each(function() {
                    var obj = $(this).parent().find('input[value="' + oddkey + '"]');

                    if (obj.length) {
                        obj.parent().parent().removeClass('alreadyBet');
                    }
                });
            }

            myBidInputBlur();
            return false;
        }

        function showEvents() {
            var dataString = $('#bettingCategoriesForm').serialize();

            $.ajax({
                type: "POST",
                url: events_url,
                data: dataString,
                dataType: 'json',
                success: function(data) {
                    if (data.error === false) {
                        $('#eventsBlock').html(data.html);

                        $('.eventAddBet').click(eventAddBetClick);
                        $('.subBetsList').click(subBetsListClick);
                    } else {
                        _alert(data.errorMessage);
                    }
                }
            });
        }

        function showEventsHomeBlock(ui) {
            var blockID = '#' + ui.panel.id;

            if ($(blockID).html() == '') {
                var dataString = [];

                switch (ui.index) {
                    case 0:
                        dataString = {
                            timeLimitStart : 0,
                            timeLimitEnd : 1
                        };
                        break;
                    case 1:
                        dataString = {
                            timeLimitStart : 0,
                            timeLimitEnd : 2
                        };
                        break;
                    case 2:
                        dataString = {
                            timeLimitStart : 0,
                            timeLimitEnd : 4
                        };
                        break;
                    case 3:
                        dataString = {
                            timeLimitStart : 0,
                            timeLimitEnd : 8
                        };
                        break;
                }

                $.ajax({
                    type: "POST",
                    url: events_url,
                    data: {
                        eventsQuery : $.toJSON(dataString),
                        activeLanguage : active_language
                    },
                    dataType: 'json',
                    success: function(data) {
                        if (data.error === false) {
                            $(blockID).html(data.html);

                            $('.eventAddBet').click(eventAddBetClick);
                            $('.subBetsList').click(subBetsListClick);
                        } else {
                            _alert(data.errorMessage);
                        }
                    }
                });

                if (!$("#ajaxLoadingBlock").is(':visible')) {
                    $("#ajaxLoadingBlock").show('fast');
                }
            }
        }

        function showPlayerProfileBlock(ui) {
            var blockID = ui.panel.id;

            if ($('#' + blockID).hasClass('static') != true) {
                showPlayerProfileBlockAjax(blockID);

                if (!$("#ajaxLoadingBlock").is(':visible')) {
                    $("#ajaxLoadingBlock").show('fast');
                }
            }

            if(ui.index==2 && $('#' + blockID).hasClass('static') == true){

                var isExist=false;
                $('#playerProfile').find('#profileDataPayForm').each(function() {
                    isExist=true;
                });
                if(!isExist){
                    getAutoPaymentBlock();
                }

            }
        }

        function showPlayerProfileBlockAjax(blockID, step) {
            $.ajax({
                type: "POST",
                url: player_url,
                data: {
                    tabKey : blockID,
                    activeLanguage : active_language,
                    step : step
                },
                dataType: 'json',
                success: function(data) {
                    if (data.error === false) {
                        $('#' + blockID).html(data.html);

                        if (blockID == 'playerBets'){
                            $('#playerBets .paging a').click(playerBetsPagingClick);
                        }
                    } else {
                        _alert(data.errorMessage);
                    }
                }
            });
        }

        function showEventsSearchBlock(searchKeyword) {
            $.ajax({
                type: "POST",
                url: events_url,
                data: {
                    searchKeyword : searchKeyword,
                    activeLanguage : active_language
                },
                dataType: 'json',
                success: function(data) {
                    if (data.error === false) {
                        $('#eventsBlock').html(data.html);

                        $('.eventAddBet').click(eventAddBetClick);
                        $('.subBetsList').click(subBetsListClick);
                    } else {
                        _alert(data.errorMessage);
                    }
                }
            });
        }

        function myBidInputBlur() {
            CountTotalStake();
            CountTotalOdds();
            CountTotalWinSimple();
            CountTotalWinMulti();


            SetBetInfoCookie();
            UpdateSession();
        }

        function CountTotalStake() {
            var stake = 0;
            $('#mySingleBets').find('input[type=text]').each(function() {
                if ( $(this).val() == '' ) {
                    $(this).val(0);
                }
                stake += parseFloat($(this).val());
            });

            stake = Math.round(stake*100)/100;
            $('#myBetsTotalSum .factor').html(stake);
        }

        function CountTotalOdds() {
            var odds = 0;
            $('#myMultiBets').find('.betOn').children('.factor').each(function() {
                if (odds == 0) {
                    odds = parseFloat($(this).html());
                } else {
                    odds = odds * parseFloat($(this).html());
                }

            });

            odds = Math.round(odds*100)/100;
            $('#myBetsTotalFactor .factor').html(odds);
        }

        function CountTotalWinSimple() {
            var win = 0;
            $('#mySingleBets li').each(function() {
                var odd = parseFloat($(this).find('.betOn').children('.factor').html());
                var stake = parseFloat($(this).find('input[type=text]').val());
                win += odd * stake;
            });

            win = Math.round(win*100)/100;
            $('#singlebet .potentialWin .sum').html(win);
        }

        function CountTotalWinMulti() {
            var win = 0;
            win = parseFloat($('#myBetsTotalFactor .factor').html()) * parseFloat($('#myBid input').val());

            win = Math.round(win*100)/100;
            $('#multibet .potentialWin .sum').html(win);
        }

        function CountTotalWinSystem() {

            var win = 0;
            var overall_stake=0;

            win = $('#sysPotentialWinnings').val();
            overall_stake=parseFloat($('#mySystemBid input').val())*parseInt($('#currOverallCount').val());
            overall_stake = Math.round(overall_stake*100)/100;
            $('#systembet .potentialWin .sum').html(win);
            $('#mySystemBetsTotalSum .overall').html(overall_stake);
        }

        function SetBetInfoCookie() {
            var activeLanguage;
            var publicnumber;
            var oddkey;
            var oddvalue;
            var oddaddvalue;
            var prefix;
            var postfix;
            var stake;

            var betsArray = [];
            $('#mySingleBets li').each(function() {
                activeLanguage = active_language;
                publicnumber = $(this).find('.publicnumber').val();
                oddkey = $(this).find('.oddkey').val();
                oddvalue = $(this).find('.oddvalue').val();
                oddaddvalue = $(this).find('.oddaddvalue').val();
                prefix = $(this).find('.prefix').val();
                postfix = $(this).find('.postfix').val();
                stake = parseFloat($(this).find('input[type=text]').val());

                betsArray.push(
                    $.toJSON({
                        activeLanguage:activeLanguage,
                        publicnumber:publicnumber,
                        oddkey:oddkey,
                        oddvalue:oddvalue,
                        oddaddvalue:oddaddvalue,
                        prefix: prefix,
                        postfix: postfix,
                        stake:stake
                    })
                    );
            });
            $.session(cookieNameSingleBet, $.toJSON(betsArray));

            var multiBetStake = parseFloat($('#myBid input').val());
            $.session(cookieNameMultiBetStake, $.toJSON({
                multiBetStake:multiBetStake
            }));

            var systemBetStake = parseFloat($('#mySystemBid input').val());
            $.session(cookieNameSystemBetStake, $.toJSON({
                systemBetStake:systemBetStake
            }));

            var selectedCombination = parseInt($("#systembet .betSystemCombinations [name=system_combination]:checked").val())?$("#systembet .betSystemCombinations [name=system_combination]:checked").val():0;
            $.session(cookieNameSystemBetInfo, $.toJSON({
                selectedCombination:selectedCombination
            }));


        }

        function FindBetInSelectedTab(selectedTab, publicnumber, oddkey) {
            var result = false;

            if (selectedTab == 0) {
                $('#mySingleBets').find('input[value="' + publicnumber + '"]').each(function() {
                    var obj = $(this).parent().find('input[value="' + oddkey + '"]');

                    if (obj.length) {
                        result = true;
                    }
                });
            } else if (selectedTab == 1 || selectedTab == 2) {
                $('#myMultiBets').find('input[value="' + publicnumber + '"]').each(function() {
                    var obj = $(this).parent().find('input[value="' + oddkey + '"]');

                    if (obj.length) {
                        result = true;
                    }
                });
            }

            return result;
        }

        function MoveSingleToMultiBet(clone) {
            if ($('#mySingleBets').find('input[type=checkbox]:checked').length) {
                $('#mySingleBets').find('input[type=checkbox]:checked').each(function() {
                    if ($(this).attr('checked')) {
                        var obj = $(this).parent().parent().parent();
                        if (clone){
                            var cloneObj = obj.clone();

                            cloneObj.find('input[type=checkbox]').remove();
                            cloneObj.find('.myBid').remove();
                            cloneObj.appendTo('#myMultiBets');
                        }
                        else {
                            obj.find('input[type=checkbox]').remove();
                            obj.find('.myBid').remove();
                            obj.appendTo('#myMultiBets');
                        }

                    }
                });

                $('.removeBet').click(removeBetClick);
                $("#myBetsBlockTabs").tabs('select', 1);
                myBidInputBlur();
            }
        }

        // messageBox

        $(".messageBox").click(function () {
            hideMessageBox();
        });

        function hideMessageBox(){
            $(".messageBox").hide('fast');
        }

        function _alert(message) {
            $(".messageBox").show('fast');
            $(".messageBox").html(message);
            setTimeout(
                function(){
                    hideMessageBox();
                }, 5000);
        }

        function checkByBarcode(){

            var barcode = $(this).parent().children('label').children('.barcodeField').val();

            if(barcode.length>0){
                $(this).parent().children('label').children('.barcodeField').css('border-color','');
                $.ajax({
                    type: "POST",
                    url: check_barcode_url,
                    data: {
                        barcode: barcode,
                        activeLanguage : active_language
                    },
                    dataType: 'json',
                    success: function(data) {
                        if (data.error === false) {

                            $('#barcodeMessageBox').html(data.html).show('fast');

                        } else {
                            _alert(data.errorMessage);
                        }
                    }
                });
            }else{
                $(this).parent().children('label').children('.barcodeField').css('border-color','red');
                $('#barcodeMessageBox').html('');
            }
        }


        function subBetsListClick() {
            var publicnumber = $(this).parent().children('.publicnumber').val();

            $.ajax({
                type: "POST",
                url: events_sub_url,
                data: {
                    publicnumber: publicnumber,
                    activeLanguage : active_language
                },
                dataType: 'json',
                success: function(data) {
                    if (data.error === false) {
                        eventsBlock = $('#eventsBlock').html();
                        $('#eventsBlock').html(data.html);

                        $('.eventAddBet').click(eventAddBetClick);
                        $('.subBetsList').click(subBetsListClick);
                        $('.eventSubBetsBack').click(eventSubBetsBackClick);
                    } else {
                        _alert(data.errorMessage);
                    }
                }
            });
        }

        function eventSubBetsBackClick() {
            $('#eventsBlock').html(eventsBlock);

            $('.eventAddBet').click(eventAddBetClick);
            $('.subBetsList').click(subBetsListClick);

            $("#homeBetTabs").tabs({
                show: function(event, ui) {
                    showEventsHomeBlock(ui);
                }
            });
        }


        // onload actions
        // load sport default events
        if ($('.sportLabel').children('input[type=checkbox]').attr('checked')) {
            obj = $('.sportLabel').parent().children('.goLink');
            obj.click();
        }


        if ($('#searchKeyword').length) {
            showEventsSearchBlock($('#searchKeyword').val());
        }

        function submitMyBidInputClick() {
            var form = $(this).parent().parent().parent().parent();
            var formKey = form.attr('id');
            var betsContainer = form.find('.myBetsForm');
            var objClass = $(this).attr('class');
            var sysBlockBetsCount=GetBlockBetsCount($('#systembet'));

            if( (sysBlockBetsCount>8 || sysBlockBetsCount<3) && formKey=='systembet' && objClass=='next'){
                objClass='disabled';
            }

            if( formKey=='systembet' && objClass=='next'){
                SetBetInfoCookie();
                UpdateSession();
            }
            switch (objClass) {
                case 'next':

                    $.ajax({
                        type: "POST",
                        async: false,
                        url: bets_action_url,
                        data: {
                            formKey : formKey,
                            activeLanguage : active_language
                        },
                        dataType: 'json',
                        success: function(data) {
                            if (data.error === false) {
                                $('#myBetsBlockTabs .tabs').hide();

                                betsContainer.html(data.html);

                                $('#myBetsBlock .submitMyBid input').click(submitMyBidInputClick);
                            } else {
                                _alert(data.errorMessage);
                            }
                        }
                    });

                    break;
                case 'back':

                    $.ajax({
                        type: "POST",
                        url: bets_action_url,
                        data: {
                            action : 'back',
                            formKey : formKey,
                            activeLanguage : active_language
                        },
                        dataType: 'json',
                        success: function(data) {
                            if (data.error === false) {
                                $('#myBetsBlockTabs .tabs').show();

                                betsContainer.html(data.html);

                                $('#myBetsBlock .submitMyBid input').click(submitMyBidInputClick);

                                $('.myBid input').rval('');
                                $('#myBid input').rval('');
                                $('#mySystemBid input').rval('');
                                $('.myBid input').blur(myBidInputBlur);
                                $('#myBid input').blur(myBidInputBlur);
                                $('#mySystemBid input').blur(myBidInputBlur);

                                $('.removeBet').click(removeBetClick);


                                myBidInputBlur();
                            } else {
                                _alert(data.errorMessage);
                            }
                        }
                    });

                    break;
                case 'placebet':
                    $('.placebet').addClass("placebet_locked").removeClass("placebet");
                    $.ajax({
                        type: "POST",
                        url: bets_action_url,
                        async: false,
                        data: {
                            action : 'placebet',
                            formKey : formKey,
                            activeLanguage : active_language
                        },
                        dataType: 'json',
                        success: function(data) {
                            if (data.error === false) {
                                $('#myBetsBlockTabs .tabs').show();

                                betsContainer.html(data.html);

                                $('#myBetsBlock .submitMyBid input').click(submitMyBidInputClick);

                                $('.myBid input').rval('');
                                $('#myBid input').rval('');
                                $('#mySystemBid input').rval('');
                                $('.myBid input').blur(myBidInputBlur);
                                $('#myBid input').blur(myBidInputBlur);
                                $('#mySystemBid input').blur(myBidInputBlur);

                                $('.removeBet').click(removeBetClick);
                                $('#mySystemBets').empty();
                                $('#myMultiBets').empty();
                                $('#mySingleBets').empty();
                                RemoveAllAlreadyBetEvents();


                                myBidInputBlur();
                            } else {
                                _alert(data.errorMessage);
                            }
                        }
                    });
                    $('.placebet_locked').addClass("placebet").removeClass("placebet_locked");

                    break;
            }

        }

        function moveSingleToMultiBetClick() {
            MoveSingleToMultiBet(false);
        }

        function cloneSingleToMultiBetClick() {
            MoveSingleToMultiBet(true);
        }

        function logOutClick() {
            $.ajax({
                type: "POST",
                url: player_login_url+'?activeLanguage='+active_language,
                data: {
                    logout : true
                },
                dataType: 'json',
                success: function(data) {
                    if (data.error === false) {
                        $('.userLogIn').html(data.html);
                    } else {
                        _alert(data.errorMessage);
                    }
                }
            });

            return false;
        }

        function profileDataFormSubmit() {
            $.ajax({
                type: "POST",
                url: player_login_url,
                data: $(this).serialize(),
                dataType: 'json',
                success: function(data) {
                    if (data.error === false) {
                        alert(data.html);
                    } else {
                        _alert(data.errorMessage);
                    }
                }
            });

            return false;
        }

        function playerBetsPagingClick() {
            var step = $(this).parent().children('input[type=hidden]').val();

            if (step >= 0) {
                showPlayerProfileBlockAjax('playerBets', step);
            }
        }

        /* Contact form BEGIN */

        $('#contactFromSubmit').click( function(submitContacts) {

            submitContacts.preventDefault();
            var reg_email = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            $('#contactName').val()?$('#contactName').css('border-color',''):$('#contactName').css('border-color','red');
            reg_email.test($('#contactEmail').val())?$('#contactEmail').css('border-color',''):$('#contactEmail').css('border-color','red');
            $('#contactCategory :selected').val()?$('#contactCategory').css('border-color',''):$('#contactCategory').css('border-color','red');
            $('#contactText').val()?$('#contactText').css('border-color',''):$('#contactText').css('border-color','red');

            if( $('#contactName').val() && reg_email.test($('#contactEmail').val()) && $('#contactCategory :selected').val() && $('#contactText').val()){

                contactFormSubmit($('#contactName').val(), $('#contactEmail').val(), $('#contactCategory :selected').val(), $('#contactText').val());

            }

        });





        function contactFormSubmit(name, email, category, text) {
            $.ajax({
                type: "POST",
                url: contact_form_url,
                data:{

                    name: name,
                    email: email,
                    category: category,
                    text: text

                },
                dataType: 'html',
                success: function(html) {

                    $('.formMessageBox').html(html).show('slow');
                    $('#contactForm').css('display','none');

                }
            });

            return false;
        }

        /* Contact form END */
        /* playerBets pay submit BEGIN */

        $('#playerBets button.playerBetSub').live( 'click',setTransferWonToBalance);

        $('.checkAllPlayerBets').live( 'click', function() {

            var checked=$(this).attr('checked');
            checkAllPlayerBets(checked);

        });

        function setTransferWonToBalance(){

            transferWonToBalance($('#playerBets'));

        }


        function transferWonToBalance(blockObj){

            var betsToPay= new Array();
            var betCounter=0;
            blockObj.find('table tr').each(function() {

                var currentBet=setUserBetsToPay($(this));

                if(currentBet){

                    betsToPay[betCounter]=currentBet;
                    betCounter++;

                }
            });

            if(betCounter>0){

                $.ajax({
                    type: "POST",
                    url: player_url,
                    data:{

                        'betsToPay[]': betsToPay,
                        activeLanguage : active_language,
                        tabKey : 'playerBetsPay'


                    },
                    dataType: 'json',
                    success: function(data) {

                        if (data.error === false) {
                            location.reload();
                        } else {
                            _alert(data.errorMessage);
                        }

                    }
                });

            }


        }


        function  setUserBetsToPay(obj){

            if(obj){

                var currentBet=false;
                var isPaid=true;

                obj.find('input.BetId').each(function() {
                    currentBet=$(this).val();
                });

                obj.find('input.BetPaidCheckbox[type=checkbox]:checked').each(function() {
                    isPaid=$(this).attr('disabled');
                });

                if(parseInt(currentBet) && isPaid===false){
                    return parseInt(currentBet);
                }else{
                    return false;
                }

            }

        }

        function checkAllPlayerBets(checked){

            $('#playerBets').find('table tr').each(function() {

                var currentBet=false;
                var isPaid=true;
                var objToCheck=true;
                $(this).find('input.BetId').each(function() {
                    currentBet=$(this).val();
                });

                $(this).find('input.BetPaidCheckbox[type=checkbox]').each(function() {
                    isPaid=$(this).attr('disabled');
                    objToCheck=$(this);

                });

                if( parseInt(currentBet) && !isPaid ){

                    checked?objToCheck.attr('checked', true):objToCheck.attr('checked', false);

                }
            });


        }


        /* playerBets pay submit END */

        /* profileAutoPayment settings BEGIN */

        $('#profileDataPayForm button').live( 'click',setAutoPayment);

        function setAutoPayment(){

            var checked=$('#profileDataPayForm label input[type=checkbox]').attr('checked')?1:0;
            if(checked===1){
                var confirmText='';
                $('#profileDataPayForm').find('input.questionSubmitText[type=hidden]').each(function() {
                    confirmText=$(this).val();
                });
                var isConfirmed=confirm(confirmText);
            }else{
                var isConfirmed=true;
            }
            if(isConfirmed){
                $.ajax({
                    type: "POST",
                    url: player_url,
                    data:{

                        autoPay: checked,
                        activeLanguage : active_language,
                        tabKey : 'playerBetsPaySettingsSet'


                    },
                    dataType: 'json',
                    success: function(data) {

                        if (data.error === false) {

                        } else {
                            _alert(data.errorMessage);
                        }

                    }
                });
            }


        }

        function getAutoPaymentBlock(){

            $.ajax({
                type: "POST",
                url: player_url,
                data:{

                    activeLanguage : active_language,
                    tabKey : 'playerBetsPaySettingsBlock'


                },
                dataType: 'json',
                success: function(data) {

                    if (data.error === false) {

                        $('#playerProfile').append(data.html);

                    } else {
                        _alert(data.errorMessage);
                    }

                }
            });


        }

        /* profileAutoPayment settings submit END */

        /* profileAutoPayment settings submit BEGIN */

        $('#profileBalanceForm button').live( 'click',confirmPaymentTransfer);

        $('#profileBalancePaymentConfirmForm button').live( 'click',confirmPaymentTransferInfo);

        function confirmPaymentTransfer() {
            setPaymentTransfer(false);
        }

        function confirmPaymentTransferInfo() {
            setPaymentTransfer(true);
        }

        function setPaymentTransfer(confirmedInfo){

            var amountToPay=confirmedInfo?parseFloat($('#profileBalancePaymentConfirmForm input.amountToPayFromBalance[type=hidden]').val().replace(/,/gi,'.')):parseFloat($('#profileBalanceForm label input[type=text]').val().replace(/,/gi,'.'));

            if(amountToPay>0){
                var currentBalance=confirmedInfo?parseFloat($('#profileBalancePaymentConfirmForm input.balanceCurrentAmount[type=hidden]').val().replace(/,/gi,'.')):parseFloat($('#profileBalanceForm label strong').text());
                var confirmText=confirmedInfo?true:false;
                var isConfirmed=confirmedInfo?true:false;
                if(!confirmText){
                    $('#profileBalanceForm').find('input.questionSubmitText[type=hidden]').each(function() {
                        confirmText=$(this).val();
                    });
                    var isConfirmed=confirm(confirmText+' '+amountToPay+' Lt.?');
                }

                if( isConfirmed && parseFloat(amountToPay)<=currentBalance ){

                    $('#profileBalanceForm label input[type=text]').css('border-color','#000000');
                    var confirmedInfoData=confirmedInfo?1:0;
                    $.ajax({
                        type: "POST",
                        url: player_url,
                        data:{

                            amountToPay: amountToPay,
                            activeLanguage : active_language,
                            tabKey : 'playerBalance',
                            amountToPayConfrimed: confirmedInfoData

                        },
                        dataType: 'json',
                        success: function(data) {

                            if (data.error === false) {
                                if(confirmedInfo===false){
                                    $('#profileBalanceForm').remove();
                                    $('#playerBalance').html(data.html);
                                }else{
                                    $('#playerBalance').html(data.html);
                                }
                            } else {
                                _alert(data.errorMessage);
                            }

                        }
                    });

                }else{
                    if(!confirmedInfo){

                        $('.balanceMessageBox').hide();
                        !isConfirmed?$('#profileBalanceForm label input[type=text]').css('border-color','#000000'):$('#profileBalanceForm label input[type=text]').css('border-color','red');
                        isConfirmed?$('#profileBalanceForm label input[type=text]').val(currentBalance):$('#profileBalanceForm label input[type=text]').val('');
                    }

                }
            }else{
                if(!confirmedInfo){

                    $('.balanceMessageBox').hide();
                    $('#profileBalanceForm label input[type=text]').css('border-color','red');
                    $('#profileBalanceForm label input[type=text]').val('');
                }

            }


        }
        /* profileAutoPayment settings submit END */

        /* Splash Screen BEGIN */

        function showSplash(){

            if( !($.cookie("importantMessageOnLogin")=='confirmed') ){

                $("#importantInformation").overlay({

                    top: 260,
                    mask: {

                        color: '#000000',
                        loadSpeed: 200,
                        opacity: 0.7,

                        zIndex: 9998
                    },

                    closeOnClick: false,
                    onBeforeClose:  $.cookie("importantMessageOnLogin", 'confirmed', {path: '/', expires: 30}),
                    load: true,
                    effect: 'default'

                });


            }
        }


    /* Splash Screen END */




    });
})(jQuery);

	// ------------------------------ END simple actions ------------------------------