function myReplaceAll(str, replace, with_this){
    return str.replace(new RegExp(replace, 'g'),with_this);
}

function myLimitStr(str,max_length){
    if(max_length > 0 && str.length > max_length)
        return str.substr(0,max_length)+' ...';
    else
        return str;
}


$(document).ready(function(){

    var profile_id = $("#wall input[name='profile_id']").val();
    var profile_type = $("#wall input[name='profile_type']").val();
    var collective = $("#wall input[name='collective']").val();
    var password_init = $("input[name='password_init']").val();

    //lighbox ze zmiana hasla dla profilu oficjalnego
    if(password_init != undefined && password_init != ''){
        $(this).overlay(457,true);
        $.get("/profile/index/change-password-lightbox",function(data){
            $(this).overlay_createBox(data);
            $(".lightbox #change-password-bt").click(function(){
                var password =  $(".lightbox form input[name='password']").val();
                var password_repeat =  $(".lightbox form input[name='password_repeat']").val();
                if(password != '' && password == password_repeat)
                    $(".lightbox form").submit();
                else
                    alert('Niepoprawnie wprowadzone hasło');
            })
        })
    }

        
    $('#wallOptions a').hover(
        function(){
            if(!$(this).children().hasClass('active'))
                $(this).children().removeClass('shareInactive');
        },function(){
            if(!$(this).children().hasClass('active'))
                $(this).children().addClass('shareInactive');
        }

        );
    $('.a_naruszenie').click(function(){
        $(this).overlay(457);
        $.get("/blogs/index/naruszenie",{
            'link': $(this).attr('href')
            },function(data){
            $(this).overlay_createBox(data);
            $("#contentAddPanel .topPart div").click(function(){
                $(this).overlay_finish();
            });
        });
        return false;
    });
    function resize_left_background(){
        if($('#inCenter #left').height() < 1230){
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left 40% #FFFFFF');
        };
        if($('#inCenter #left').height() < 500){
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left 25% #FFFFFF');
        };
    }
    
    $('#right').resize(function(){
        if($('#inCenter #right').height()>$('#inCenter #left').height()){
            $('#inCenter #left').height($('#inCenter #right').outerHeight());
        }
    });
    $('#right').resize();

    $('#left').resize(function(){
        if($('#inCenter #right').height()>$('#inCenter #left').height()){
            $('#inCenter #left').height($('#inCenter #right').outerHeight());
        }else{
            $('#inCenter #left').innerHeight($('#inCenter #left').outerHeight());
        }
        resize_left_background();
    });
    $('#left').resize();

    resize_left_background();
	
    $('.prediction').live('click',function(){
        var container=$(this).parents('.typeDiv');
        $('.type').hide();
        container.find('.type').show()
        //$('.type').show();
        return false;
    });
	
    /*$('.type').live('click',function(){
        var predictionArray='{';
        var i=0;
        var length=0;
        var button=$(this);
        $('.prediction').each(function(e){
            if($(this).val() && $(this).next().val() && $(this).attr('id')==$(this).next().attr('id')){
                length+=1;
            }
        });
        $('.prediction').each(function(e){
            if($(this).val() && $(this).next().val() && $(this).attr('id')==$(this).next().attr('id')){
                //var predict='';
                predictionArray+= '"'+i+'":{"idMatch":'+$(this).attr("id")+',"localscore":'+$(this).val()+',"visitorscore":'+$(this).next().val()+'}';
                if(length>1 && length!=i+1)
                    predictionArray+=','
                i++;
            }
        });
        //alert(predictionArray);
        predictionArray+= '}';
        $.post('/league/prediction/type',{
            'predictionArray':predictionArray
        },function(){
                    
            if(button.hasClass('typeReload'))
                location.reload();
            else
                alert("Wyniki zapisano");
        });
                
	
    });*/

    $('.localteamFanPredict').hover(
        function(){
            $('.localteamFanChart').show()
            },
        function(){
            $('.localteamFanChart').hide()
            }
        );
    $('.visitortemaFanPredict').hover(
        function(){
            $('.visitorteamFanChart').show()
            },
        function(){
            $('.visitorteamFanChart').hide()
            }
        );
    /* standings hover */
    $('.standingsMatch tr, .lastMatches tr,.teamMatchesTable tr').live('mouseover',
        function(){
            $(this).children().css({
                'background':'#CEE2A7',
                'cursor':'pointer'
            });
        }
        );
    $('.standingsMatch tr, .lastMatches tr,.teamMatchesTable tr').live('mouseout',
        function(){
            var bg = $(this).attr('rel');
            $(this).children().css({
                'background':bg,
                'cursor':'pointer'
            });
        // $(this).children('.visitorScore,.localScore, .scoreDot').css({'background':bg,'cursor':'pointer','color':'#6A9B07'});
        // $(this).children('.score, .data, .date, .localteamName, .visitorteamName').css({'background':bg,'cursor':'pointer','color':'#636363'});
        }
        );
    $('#messagePanel .thread-item').live('click',
        function(event){
            if ( !$(event.target).is('a') ) {
                location.href=$(this).attr('rel')
            }
    });
    $('.standingsMatch tr,  .lastMatches tr,.teamMatchesTable tr').live('click',
        function(event){
            if ( !$(event.target).is('a') ) {
                location.href=$(this).attr('id')
            }
        }
        )
    $('.liveMatches tr').live('click',function(event){
        if ( !$(event.target).is('a') ) {
            var match=$(this).attr('id');
            $('.stats-'+match).toggle();
        }
    });
    $('.mainSearchResults').live('click',function(event){
        if ( !$(event.target).is('a') && $(this).parent().attr('id')!='left') {
            location.href=$(this).attr('rel');
        }
    });
    /* change stage in cup*/
    $('.cupButton').live('click',
        function(){
            $('.roundMatch').ajaxSend(function() {
                $('#loader2').show();
            });
            //$('.standingsMatch').hide();
            //$('.roundMatch2').hide();
            $('.cupButton').removeClass('cupButtonActive');
            $(this).addClass('cupButtonActive');
            $.get($(this).attr('id'),{},function(resp){
                $('#loader2').hide();
                $('.roundMatch2').html(resp);
                //$('.roundMatch2').show();
                $('.roundMatch2').load(function(){
                    //$('.standingsMatch').show();
                });
                $('#inCenter #left').css("height","100%");
                $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');
            });



        }
    );
        
    $('.stageButton').live('click',
        function(){
            $('#loader2').show();
            $('.stageButton').removeClass('stageButtonActive');
            $(this).addClass('stageButtonActive');
            
            $.get($(this).attr('id'),{},function(resp){
                $('#loader2').hide();
                $('.roundMatch2').html(resp);
                $('#inCenter #left').css("height","100%");
                $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');
            });
        }
    );
        
        
    /* change stage in cup*/
    $('.teamMatchesButton').live('click',
        function(){
            $('#loader').show();
            //$('.toUpdate').hide();
            $('.teamMatchesButton').removeClass('selected');
            $(this).addClass('selected');
            $.get($(this).attr('id'),{},function(resp){
                $('#loader').hide();
                $('.toUpdate').html(resp);
                //$('.toUpdate').show();
                $('#inCenter #left').css("height","100%");
                $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');

            });



        }
    );
    $('.tabs li').live('click',
        function(){
            $('.standingsMatch').ajaxSend(function() {
                $('#loader2').show();
            });
            //$('.tab_content').hide();
            $('.tabs li').removeClass('active');
            $(this).addClass('active');
            $.get($(this).attr('id'),{},function(resp){
                $('#loader2').hide();
                $('.tab_content').html(resp);
                //$('.tab_content').show();
                $('#inCenter #left').css("height","100%");
                $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');

            });



        }
        );
    /* next prev round */
    $('.rightA, .leftA').live('click',
        function(){
            $('.standingsMatch').ajaxSend(function() {
                //if($('.roundMatch').find('#loader'))
                $('#loader').show();
                //else
                $('#loader2').show();
            });
            //$('.standingsMatch').hide();
            week = $(this).attr('rel');
            $.get($(this).attr('id'),{
                load:'round',
                week:week
            },function(resp){
                //alert(resp);
                $('#loader').hide();
                $('#loader2').hide();
                $('.roundMatch').html(resp);
                $('.roundMatch').load(function(){
                    //$('.standingsMatch').show();
                });
                $('#inCenter #left').css("height","100%");
                $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');
            });
			
			
		
        }
        );
	
    /* select round  list */
	
    $("#selectRounds").live('change',function () {
        $('.standingsMatch').ajaxSend(function() {
            $('#loader').show();
            $('#loader2').show();
        });
        link = $('#selectRounds option:selected').attr('id');
        //$('.standingsMatch').hide();
        $.get(link,{
            load:'round'
        },function(resp){
            $('#loader').hide();
            $('#loader2').hide();
            $('.roundMatch').html(resp);
            $('#inCenter #left').css("height","100%");
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');

           // $('.standingsMatch').show();
        });
    });
	
	
	
	
	
    /* PRZELACZANIE TYGODNI W LIGACH */
	
    $("#nextMatches, #prevMatches").live('click',function(){
        url = $(this).attr('rel');
        //$('.lastMatchesDiv').hide();
        $('#loader').show();
        $.get(url,{
            'onlyTable':1
        },function(resp){
            $('.lastMatchesDiv').html(resp);
            $('#loader').hide();
            $('#inCenter #left').css("height","100%");
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');

            //$('.lastMatchesDiv').show();
        });
    });
	
    $("#nextWeekT, #prevWeekT").live('click',function(){
        url = $(this).attr('rel');
        //$('.lastMatchesDiv').hide();
        $('#loader').show();
        $.get(url,{
            'onlyTable':1
        },function(resp){
            $('.lastMatchesDiv').html(resp);
            $('#loader').hide();
            $('#inCenter #left').css("height","100%");
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');

            //$('.lastMatchesDiv').show();
        });

    });

    $(".smallButton a").mouseover(function(){
        $(this).children(".leftCorner").css("background", 'url("/public/images/gfx/_small_menu_left.png")');
        $(this).children(".center").css("background", 'url("/public/images/gfx/_small_menu_center.png")');
        $(this).children(".rightCorner").css("background", 'url("/public/images/gfx/_small_menu_right.png")');
        $(this).children().css("color","#FFF")

    });
    $(".smallButton a").mouseout(function(){
        if(!$(this).hasClass("selected")){
            $(this).children(".leftCorner").css("background", 'url("/public/images/gfx/small_menu_left.png")');
            $(this).children(".center").css("background", 'url("/public/images/gfx/small_menu_center.png")');
            $(this).children(".rightCorner").css("background", 'url("/public/images/gfx/small_menu_right.png")');
            $(this).children().css("color","#ADABAB")
        }
    });
    /*$(".smallButton a").click(function(){
            $(this).addClass("selected");
        });*/
    /*$(".btShowFriendsBox").click(function(){
        $('#leftMenuContent li').removeClass('selected');
        $(this).parent().attr("class", "selected")
        $(this).children("img").attr("src", "/public/images/layout2/teams/_ludek.png")
    });*/

    $("div.flag").click(function(){
        var nr=$(this).attr("rel");
        var wiersz = $('.flag [rel="'+nr+'"]');
        var arrow=wiersz.children().children('.arrow');
        $(".flag").each(function(){
            if($(this).attr("rel")==nr){
                var arrow=$(this).find('.arrow');
                if(arrow.hasClass("arrowDown")){
                    arrow.removeClass("arrowDown");
                    arrow.addClass("arrowUp");
                    //$(this).parent().height(h);
                    $(".league-"+nr).show();
                }else{
                    arrow.removeClass("arrowUp");
                    arrow.addClass("arrowDown");
                    $(".league-"+nr).hide();
                }
            }
        });
        $('#inCenter #left').css("height","100%");
        $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');

    });
    $('.rollDownAll').live('click',function(){
        $(this).hide();
        $('.rollUpAll').show();
        $('.arrow').removeClass("arrowDown");
        $('.arrow').addClass("arrowUp");
        $(".leaguesInCountry").show();
        $('#inCenter #left').css("height","100%");
        $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');
    });
    $('.rollUpAll').live('click',function(){
        $(this).hide();
        $('.rollDownAll').show();
        $('.arrow').removeClass("arrowUp");
        $('.arrow').addClass("arrowDown");
        $(".leaguesInCountry").hide();
        $('#inCenter #left').css("height","100%");
        $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');
    });
    if($('#search_league').is("input")){
        $('#search_league').autocomplete({
            serviceUrl:'/league/index/suggest',
            minChars:1,
            width:460,
            maxHeight:400,
            onSelect: function(value, data){
                var dane=data.split('-');
                var type=dane[0];
                var id=dane[1];
                $("#searchForm").find("input[name='sid']").val(id);
                if(type=='l')
                    $('#searchForm').attr('action','/league/index/show/id/'+id);
                if(type=='tt' || type=='tn' || type=='q')
                    $('#searchForm').attr('action','/tournament/index/show/id/'+id);
                if(type=='ct' || type=='cn')
                    $('#searchForm').attr('action','/cup/index/show/id/'+id);
            }
        });
    }
    $('#search_league').click(function(){
        if ($(this).val() == 'Wyszukaj w ligach') $(this).val('');
    });
    $('.tableMore').click(function(){
        $('.standingsTable tr').show();
        $(this).hide();
        $('.tableLess').show();
    });

    $('.tableLess').click(function(){
        $('.standingsTable tr[rel=hidden]').hide();
        $(this).hide();
        $('.tableMore').show();
    });
    $('.matchMore').live('click',function(){
        $('.lastMatchesDiv .lastMatches tr').show();
        $(this).hide();
        $('.matchLess').show();
    });
    $('.matchLess').live('click',function(){
        $('.lastMatchesDiv .lastMatches tr.hidden').hide();
        $(this).hide();
        $('.matchMore').show();
    });
    $('#wyslij-wiadomosc').live('click',function(){
        var form=$('#wiadomosc-form');
        if($('.as-values').val()!='')
            jQuery.post('/mail/to/send',form.serialize(),function(data){
                $("#imageAddPanel #tresc").html(data);
            });
    });
    $('.news-more').live('click',function(){
        $('#news .news_in').show();
        $(this).hide();
        $('#inCenter #left,#inCenter #right').height( Math.max($('#inCenter #left').outerHeight(),$('#inCenter #right').outerHeight()) );
    });
    $("#profile-naruszenie-bt").click(function(){
        $(this).overlay(457);
        var profile_id=$(this).attr('rel');
        $.get("/profile/index/naruszenie",{
            'profile_id':profile_id
        },function(data){
            $(this).overlay_createBox(data);
            $(this).overlay_center();
            $("#contentAddPanel .topPart div").click(function(){
                $(this).overlay_finish();
            });
            $("#naruszenie-send-form .bt").click(function(){

                if($("#naruszenie-moderator-box form input[name='descr']").val() == ''){
                    alert("Uzupełnij opis");
                    return false;
                }

                $("#naruszenie-send-form").submit();
            });

        })
        return false;
    });
    $('.season select').live('change',function(){
        $('#loader2').show();
        link = $(this).val();
        //$('.updateSeason').hide();
        $.get(link,{'changeSeason':1},function(resp){
            $('.updateSeason').html(resp);
            //$('.updateSeason').show();
            $('#loader2').hide();
            $('#inCenter #left').css("height","100%");
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');
        });
        /*var season=$(this).val();
        var url2=new String(window.location);
        var url=url2.replace('#','');
        if(url.search("season")>=0){
            var urlArray=url.split('?season=');
            window.location=urlArray[0]+'?season='+season;
        }else{
            window.location=url+'?season='+season;
        }*/
            
    });
    $('.advancedSearch').click(function(){
        $('.advancedTerms').toggle();
        $('.advancedArrow').toggle();
    });
    $('#teams_country').change(function(){
        var id_country=$(this).val();
        $('#advancedLoader').show();
        $.getJSON('/teams/index/getleaguesincountry/', {
            'country':id_country
        }, function(data){
            $('#teams_league option').remove();
            $("#teams_league").append('<option value="0" >jakakolwiek</option>');
            $.each(data, function(id,name){
                $("#teams_league").append('<option value="' + id +'" >'+name+'</option>');
            });
            $('#advancedLoader').hide();
            $('#inCenter #left').css("height","100%");
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');

        });
    });
    $('#players_country').change(function(){
        var id_country=$('#players_country').val();
        $('#advancedLoader').show();
        $.getJSON('/player/index/getleaguesorteams/', {
            'country':id_country
        }, function(data){
            $('#players_league').find('option').remove();
            $("#players_league").append('<option value="0" >jakakolwiek</option>');
            $.each(data.league, function(id,name){
                $("#players_league").append('<option value="' + id +'" >'+name+'</option>');
            });
            $('#players_team').remove();
            $('#players_team_label').after('<select name="team" id="players_team"></select>').end();
            $('#players_team').append('<option value="0" >jakakolwiek</option>');
            $.each(data.team, function(id,name){
                $("#players_team").append('<option value="' + id +'" >'+name+'</option>');
            });
            $('#advancedLoader').hide();
            $('#inCenter #left').css("height","100%");
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');

        });
    });
    $('#players_league').change(function(){
        var id_country=$('#players_country').val();
        var id_league=$('#players_league').val();
        $('#advancedLoader').show();
        $.getJSON('/player/index/getleaguesorteams/', {
            'country':id_country,
            'league':id_league
        }, function(data){
            $('#players_team').remove();
            $('#players_team_label').after('<select name="team" id="players_team"></select>').end();
            $("#players_team").append('<option value="0" >jakakolwiek</option>');
            $.each(data.team, function(id,name){
                $("#players_team").append('<option value="' + id +'" >'+name+'</option>');
            });
            $('#advancedLoader').hide();
            $('#inCenter #left').css("height","100%");
            $('#left').css('background','url("/public/images/gfx/left_bg.jpg") repeat-x scroll left bottom #FFFFFF');
        });
    });


    /*$("#mainQuery").keyup(function(){
            var searchbox = $(this).val();
            var dataString = 'query='+ searchbox+'&short=1';
            $("#mainSearchResult").html('<div style="background:white" class="center">Loading...</div>').show();
            if(searchbox!=''){
                $.ajax({
                    type: "POST",
                    url: "/index/search/",
                    data: dataString,
                    cache: false,
                    success: function(html){
                        $("#mainSearchResult").empty();
                        $("#mainSearchResult").html(html).css('border','1px solid #AEACAC').show();
                    }
                });
            }
            return false;
        });*/
    $("#mainQuery").focus(function(){
        if($(this).val()=='Szukaj')
            $(this).val('');
    });
    $("#mainQuery").blur(function(){
        if($(this).val()=='')
            $(this).val('Szukaj');
        $('#mainSearchResult').hide();
    });
    $(".mainSearchForm").submit(function(){
        if($('#mainQuery').val()=='Szukaj' || $("#mainQuery").val()=='')
            return false;
        return true;
    });

    /*if($('#mainQuery').is("input")){
        $('#mainQuery').mainsearch({
            serviceUrl:'/index/search/',
            minChars:3,
            width:258
        });
    };*/
        
});


(function($){

    jQuery.extend({
        newPostsAjax: {
            id: 'new_posts',
            ready: function(){

                return $("#wall input[name='collective']").val() == true;
            },
            beforeSend: function(){
            },
            success: function(data){

                if(data['last_date'] != $("#wall .threads").children("li:first").find("input[name='thread_date']").val())
                    $("#wallOptions #bt-new-posts .shareCenter #post-cnt").html(data['cnt']);
            },
            error: function(){
            }

        },
        checkLoginAjax: {
            id: 'check_login',
            ready: function(){
                return true;
            },
            beforeSend: function(){
                return true;
            },
            success: function(data){
                if(data==false){
                    window.location='/';
                }
            },
            error: function(){
                return true;
            }

        }
    })

    jQuery.fn.extend({
        generateHash: function(len){
            var hash = Math.random();
            for(i=0;i<len;i++)
                hash *= 10;
            return Math.floor(hash);
        },
        URLEncode:function(c){
            var o='';
            var x=0;
            c=c.toString();
            var r=/(^[a-zA-Z0-9_.]*)/;
            while(x<c.length){
                var m=r.exec(c.substr(x));
                if(m!=null && m.length>1 && m[1]!=''){
                    o+=m[1];
                    x+=m[1].length;
                }else{
                    if(c[x]==' ')o+='+';
                    else{
                        var d=c.charCodeAt(x);
                        var h=d.toString(16);
                        o+='%'+(h.length<2?'0':'')+h.toUpperCase();
                    }
                    x++;
                }
            }
            return o;
    },
    URLDecode:function(s){
        var o=s;
        var binVal,t;
        var r=/(%[^%]{2})/;
        while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){
            b=parseInt(m[1].substr(1),16);
            t=String.fromCharCode(b);
            o=o.replace(m[1],t);
        }
        return o;
    }
    })
})(jQuery);



/*
 * Zamieszczam tutaj poniewaz nie mam zielonego pojecia jak wy dzielicie i gdzie trzymacie podstawowe wywolania JQ
 */
function overlayFinish(){
    $('#jquery-container-box').remove();
}




