var act_sport = 'foot';
var act_min = 0;
var act_max = 100;
var act_bookmakers = '';
var isInited = false;

$().ready(function(){
    //init();
    initFilter();
});

function initFilter(){
    $('#dialog-filter_removed').dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        height: 130,
        width: 300
    });
    //MRUGANIE
    //Non-Plugin Function
    var doBlink = function(obj,start,finish) {
        jQuery(obj).fadeOut(500).fadeIn(500);if(start!=finish) {
            start=start+1;doBlink(obj,start,finish);
        }}

    //jQuery Blink Plugin
    jQuery.fn.blink = function(start,finish) {
        return this.each(function() {
            doBlink(this,start,finish)});
    }

    var aSports = ['foot', 'mlb', 'hoc', 'basket'];

    ///////////////////////////////////////////
    ////////Podpiecie kalendarzy//////////////
    /////////////////////////////////////////
    for (var key in aSports) {
        podepnijKalendarzById(aSports[key]+'_zakres_daty_od',lang['page_lang'],'yy-mm-dd',null);
        podepnijKalendarzById(aSports[key]+'_zakres_daty_do',lang['page_lang'],'yy-mm-dd',null);
    }

    ///////////////////////////////////////////
    //////ZAZNACZANIE ODZNACZQNIE WSZYSTKICH//
    /////////////////////////////////////////
    initBookFilter();
    initProfitFilter();
    initMatchStartTimeFilter();
    initToggleFilterMenu();
    initRemoveFilters();
    $('input.book_filter').click(function(){
        $(this).parents('table').find('span.book_filter_info').show('blind');
    });

    $('button.clear_czas_filter').click(function(){
        $(this).parents('div.time_filter').find('input').val('');
        $(this).parents('div.time_filter').find('select').val(0);
        $(this).parents('div.time_filter').find('button.czas_filter').click();
        $('#second_filter').find('div.profit_filter input').val('');
        var sSport = $('#second_filter input.sport_kind').val();
        $('#s_'+sSport+'_table tbody tr:hidden').show();
        filtrowaniePoZysku(sSport);
        checkMatchStartTimeBorder(sSport);
    });

    /////////////////////////////////////////////
    ///////ODPALENIE FILTROW////////////////////
    ///////////////////////////////////////////
    filtrowaniePoZysku('foot');
   // filtrowaniePoZysku('basket');
    filtrowaniePoZysku('mlb');
    filtrowaniePoZysku('hoc');


    $('span.f_nowosc').blink(1,6);
}

function showFilterRemoveMessage(){
    $('#dialog-filter_removed').dialog('open');
}

function initRemoveFilters(){
    $('#remove_filter_foot').click(function(){
        removeFilter('foot');
         return false;
    });
    $('#remove_filter_basket').click(function(){
        removeFilter('basket');
         return false;
    });
    $('#remove_filter_mlb').click(function(){
        removeFilter('mlb');
         return false;
    });
    $('#remove_filter_hoc').click(function(){
        removeFilter('hoc');
         return false;
    });
}

function removeFilter(sSport){
    $('#s_filter_'+sSport+'_body').find('div.time_filter input').val('');
    $('#s_filter_'+sSport+'_body').find('div.time_filter select').val(0);
    $('#'+sSport+'_zakres_zysku_od').val('');
    $('#'+sSport+'_zakres_zysku_do').val('');
    $('#choose_bookmaker_'+sSport+' input:checkbox').not('#sa_'+sSport+'_select_all').attr('checked',true);

    checkIfMin2Books(sSport, true);
    checkIfFiltrIsOn(sSport);
    if($('#s_'+sSport+'_table tbody tr:visible').length < 1){
        $('#'+sSport+'_filter_footer_error').show();
    }else{
        $('#'+sSport+'_filter_footer_error').hide();
    }
}

function checkIfFiltrIsOn(sSport){
    var iSelected = $('#choose_bookmaker_'+sSport+' input:checkbox:checked').not('#sa_'+sSport+'_select_all').length;
    var iAllCheckboxes = $('#choose_bookmaker_'+sSport+' input:checkbox').not('#sa_'+sSport+'_select_all').length;
    var fZyskOd = $('#'+sSport+'_zakres_zysku_od').val();
    var fZyskDo = $('#'+sSport+'_zakres_zysku_do').val();
    var isFilter = false;

    if((iAllCheckboxes - iSelected) != 0){
        isFilter = true;
    }

    if(fZyskDo != '' || fZyskOd != ''){
        isFilter = true;
    }

    if(isFilter == true){
        var visible_surebets = $('#s_'+sSport+'_table tbody tr.w_main_row:visible').length;
        var sport_surebets = $('#'+sSport+'_surebets_amount').val();
        $('#'+sSport+'_filtr_aktywny:hidden').show('blind');
         $('#'+sSport+'_filtr_aktywny span').text(visible_surebets+'/'+sport_surebets)
    }else{
        $('#'+sSport+'_filtr_aktywny:visible').hide('blind');
    }
}


function initToggleFilterMenu(){
    //ukrywanie panelu filtra
    $('#foot_data_filter_bt').click(function(){
        $('#s_filter_foot_body').toggle('blind');
        $('#foot_ukryj').toggle();
    });
    $('#mlb_data_filter_bt').click(function(){
        $('#s_filter_mlb_body').toggle('blind');
        $('#mlb_ukryj').toggle();
    });
    $('#hoc_data_filter_bt').click(function(){
        $('#s_filter_hoc_body').toggle('blind');
        $('#hoc_ukryj').toggle();
    });
    $('#basket_data_filter_bt').click(function(){
        $('#s_filter_basket_body').toggle('blind');
        $('#basket_ukryj').toggle();
    });
}

function initMatchStartTimeFilter(){
    $('#id_foot_czas_filter').click(function(){
        $('#id_foot_zysk_filter').click();
    });
    $('#id_mlb_czas_filter').click(function(){
        $('#id_mlb_zysk_filter').click();
    });
    $('#id_hoc_czas_filter').click(function(){
        $('#id_hoc_zysk_filter').click();
    });
    $('#id_basket_czas_filter').click(function(){
        $('#id_basket_zysk_filter').click();
    });
}

function checkMatchStartTimeBorder(sSport){
    var czas_od = $('#ts_'+sSport+'_zakres_daty_od').val();
    var czas_do = $('#ts_'+sSport+'_zakres_daty_do').val();
    var godzina_od = $('#'+sSport+'_zakres_godzin_od').val();
    var godzina_do = $('#'+sSport+'_zakres_godzin_do').val();

    czas_od = parseInt(czas_od)/1000 + (parseInt(godzina_od)*3600);
    czas_do = parseInt(czas_do)/1000 + (parseInt(godzina_do)*3600);

     $('#s_'+sSport+'_table tbody td.match').each(function(){
        var val = parseInt($(this).attr('title'));
        //alert('zysk: '+val+' min: '+min+' max: '+max);
        if(val < czas_od || val > czas_do){
            $(this).parent().hide()
                            .next().hide();
        }
    });
}

function storeUserSurebetsFilter(sSport){
    var aBookmakers = new Array();
    var aCheckboxes = $('#choose_bookmaker_'+sSport+' input:checkbox:checked').not('#sa_'+sSport+'_select_all');
    var sBookmakers = '0';
    var iUserId = $('#user_id').val();
    var fZyskOd = $('#'+sSport+'_zakres_zysku_od').val().replace(',', '.');
    var fZyskDo = $('#'+sSport+'_zakres_zysku_do').val().replace(',', '.');

    aCheckboxes.each(function(){
        aBookmakers.push($(this).val());
    });

    sBookmakers = aBookmakers.join(',');
    //alert(sBookmakers+' ID: '+iUserId+' zOD: '+fZyskOd+' zDO: '+fZyskDo);
    $.post("/files/saveUserSurbetFilter.php",{f_bookmakers: sBookmakers,
                                       f_user_id: iUserId,
                                       f_zysk_od:fZyskOd ,
                                       f_zysk_do:fZyskDo,
                                       f_sport: sSport},
                                       function(data){
                                           // alert('Store: '+data);
                                       });
}

function podepnijKalendarzById(id,lang,format,maxdate){
    if(lang == 'pl'){
        $("#"+id).datepicker({
                        dateFormat: format,
                        dayNames: ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
                        dayNamesShort: ['Ni','Po','Wt','Śr','Cz','Pt','So'],
                        dayNamesMin: ['Ni','Po','Wt','Śr','Cz','Pt','So'],
                        monthNames: ['Styczeń','Luty','Marzec',
                                     'Kwiecień','Maj','Czerwiec',
                                     'Lipiec','Sierpień', 'Wrzesień',
                                     'Październik', 'Listopad', 'Grudzień'],
                        monthNamesShort: ['Sty', 'Lut', 'Marz',
                                          'Kwi','Maj','Cze',
                                          'Lip','Sie','Wrze',
                                          'Paź','Lis','Gru' ],
                        nextText: 'Następny',
                        prevText: 'Poprzedni',
                        maxDate: maxdate,
                        altField: '#ts_'+id,
                        altFormat: '@'

                     });
    }else{
        $("#"+id).datepicker({
                        dateFormat: format,
                        maxDate: maxdate,
                        altField: '#ts_'+id,
                        altFormat: '@'
                     });
    }
}

function initProfitFilter(){
    $('#id_foot_zysk_filter').click(function(){
        $('#s_foot_table tbody tr:hidden').show();
        filtrowaniePoZysku('foot');
        checkMatchStartTimeBorder('foot');
        storeUserSurebetsFilter('foot');
    });
    $('#id_mlb_zysk_filter').click(function(){
        $('#s_mlb_table tbody tr:hidden').show();
        filtrowaniePoZysku('mlb');
        checkMatchStartTimeBorder('mlb');
        storeUserSurebetsFilter('mlb');
    });
    $('#id_hoc_zysk_filter').click(function(){
        $('#s_hoc_table tbody tr:hidden').show();
        filtrowaniePoZysku('hoc');
        checkMatchStartTimeBorder('hoc');
        storeUserSurebetsFilter('hoc');
    });
    $('#id_basket_zysk_filter').click(function(){
        $('#s_basket_table tbody tr:hidden').show();
        filtrowaniePoZysku('basket');
        checkMatchStartTimeBorder('basket');
        storeUserSurebetsFilter('basket');
    });
}

function initBookFilter(){
    $('#sa_foot_select_all').change(function(){
        if($(this).is(':checked')){
            $('#choose_bookmaker_foot input.book_filter:not(:checked)').attr('checked', true);
        }else{
            $('#choose_bookmaker_foot input.book_filter:checked').removeAttr('checked');
        }
        $('#foot_book_filter_info:hidden').show('blind');
    });

    $('#sa_basket_select_all').change(function(){
        if($(this).is(':checked')){
            $('#choose_bookmaker_basket input.book_filter:not(:checked)').attr('checked', true);
        }else{
            $('#choose_bookmaker_basket input.book_filter:checked').removeAttr('checked');
        }
        $('#basket_book_filter_info:hidden').show('blind');
    });

    $('#sa_hoc_select_all').change(function(){
        if($(this).is(':checked')){
            $('#choose_bookmaker_hoc input.book_filter:not(:checked)').attr('checked', true);
        }else{
            $('#choose_bookmaker_hoc input.book_filter:checked').removeAttr('checked');
        }
        $('#hoc_book_filter_info:hidden').show('blind');
    });

    $('#sa_mlb_select_all').change(function(){
        if($(this).is(':checked')){
            $('#choose_bookmaker_mlb input.book_filter:not(:checked)').attr('checked', true);
        }else{
            $('#choose_bookmaker_mlb input.book_filter:checked').removeAttr('checked');
        }
        $('#mlb_book_filter_info:hidden').show('blind');
    });
}

function reFilter(sSport){
    filtrowaniePoZysku(sSport);
    checkMatchStartTimeBorder(sSport);
    storeUserSurebetsFilter(sSport);
}


function reColorRows(){
    $('table.tble tbody tr.w_main_row:visible:even').css('background-color','#FAFAFA');
    $('table.tble tbody tr.w_main_row:visible:odd').css('background-color','#ECECEC');
}

function checkIfMin2Books(sSport, removeFilter){
    var selectedBooks = $('#choose_bookmaker_'+sSport+' input.book_filter:checked').length;
    if(selectedBooks > 1){
        $('#'+sSport+'_book_filter_info:visible').hide('blind');
        xajax_fx.getSurebets(xajax.getFormValues('choose_bookmaker_'+sSport), sSport, removeFilter);
    }else{
        var old_text = $('#'+sSport+'_book_filter_info').text();
        $('#'+sSport+'_book_filter_info').text(lang['zaznacz_min_2_book']);
        $('#'+sSport+'_book_filter_info:hidden').show('blind');
        setTimeout(function(){
                 $('#'+sSport+'_book_filter_info:visible').hide('blind',function(){
                        $('#'+sSport+'_book_filter_info').text(old_text);
                    });
            }, 3000);
    }
}

function filtrowaniePoZysku(sSport){
    if($('#'+sSport+'_zakres_zysku_od').length > 0){
        var min = parseFloat($('#'+sSport+'_zakres_zysku_od').val().replace(',', '.'));
        var max = parseFloat($('#'+sSport+'_zakres_zysku_do').val().replace(',', '.'));
        //sprawdzanie wprowadzonych wartosci
        //ukrywanie wierszy
        if(max > 0){
            if(min > max){
                $('#'+sSport+'_zakres_zysku_od').val(max);
                $('#'+sSport+'_zakres_zysku_do').val(min);
                max = min;
                min = $('#'+sSport+'_zakres_zysku_od').val();
            }

            $('#s_'+sSport+'_table tbody td.zysk').each(function(){
                var val = parseFloat($(this).text());
                //alert('zysk: '+val+' min: '+min+' max: '+max);
                if(val < min || val > max){
                    $(this).parent().hide()
                                    .next().hide();
                }
            });
        }

        if($('#s_'+sSport+'_table tbody tr:visible').length < 1){
            $('#'+sSport+'_filter_footer_error').show();
        }else{
            $('#'+sSport+'_filter_footer_error').hide();
        }

        reColorRows();
        checkIfFiltrIsOn(sSport);
    }
}


