
$(document).ready(function() {
    $("#data_przypisania").datepicker({
        dateFormat: 'yy-mm-dd',
        firstDay: 1
    });

    /**
    * Wyświetlanie panelu logowania
    */
    $("#login_button").click(function() {
        var login = $("#login_form").html();
        $("#popup_alert span").html(login);
        $("#popup_alert").show();
        widthPopup();
        return false;
    });

    $("#nazwa_prezentu,#www,#opis").focus(function() { 
        $(this).val('');
        $(this).removeClass('unchanged');
    })
    $("#nazwa_prezentu, #www,#opis").blur(function() {
        komunikaty_item = $(this).attr('id')+"_field"
        if($(this).val()=='') {
            $(this).val(komunikaty[komunikaty_item]);
            $(this).addClass('unchanged');
        };
    })
    $("#nazwa_prezentu").change(function() { 
        $(this).removeClass('unchanged');
    })
    $(".pytaj").click(function() {
        val = $("#www").val();
        $.post('/pl/prezenty/obrazki/format/html', {
            url: val
        }, function(data) {
            $("#photos_field ul").hide();
            $("#photos_field ul").html(data);
            $("#photos_field ul").show();

        });
        return false;
    })

    //    $(".register_button, .top_extra_button").click(function() {
    //        $("#register_div_form").fadeIn('slow');
    //        return false;
    //    });

    $("#cloud_container .button, #normal_container .button").click(function() {
        if($("#dodaj_prezent_form").length!=0) {
            nazwa_prezentu = $('#nazwa_prezentu').val();
            if(nazwa_prezentu=='' || $("#nazwa_prezentu").is('.unchanged')) {
                alert(komunikaty.nazwa_niepusta);
                return false;
            }
            $("#dodaj_prezent_form #nazwa").val(nazwa_prezentu);
            podpowiedz_obrazek();
            wyczysc_formularz_prezentu();
            $("#dodaj_prezent_form").fadeIn('slow');
        } else {
            var login = $("#login_form").html();
            $("#popup_alert span").html(login);
            $("#popup_alert").show();
            widthPopup();
        }
        return false;
    })

    $('.edit_prezent').live('click', function() {
        href=$(this).attr('href');

        $.getJSON(href, {}, function(json) {
            wyczysc_formularz_prezentu();
            
            $("#nazwa").val(json.nazwa);
            if(json.www!='') {
                $("#www").val(json.www);
            }
            if(json.opis!='') {
                $("#opis").val(json.opis);
            }
            if(json.foto!='default.gif') {
                $("#photos_field ul").append("<li class='wybrany'> <div class='table-cell'><a class='nowe_foto' href='"+json.foto+"'><img src='/_p/upload/100_"+json.foto+"' alt='' /></a></div></li>");
                $("#foto_stare").val(json.foto);
            }
            $("#foto_id").val(json.id);
            $("#dodaj_prezent").addClass('edit');
            $("#dodaj_prezent_form").fadeIn('slow');
        })
        return false;
    })
    
    $(".close_button").live('click', function() {
        $(this).parent().fadeOut();
        return false;
    })
    $(".close").live('click', function() {
        $('.short_msg').fadeOut();
        return false;
    });

    /**
    * Wyświetlanie chmurki podpowiedzi
    */
    $("a.help_button").mouseover(function() {
        txt = $(this).children('span').html();
        $(this).parent('.button').append("<div class=\"cloud\"><h3>"+komunikaty.podpowiedz+"</h3><p>"+txt+"</p></div>");
        $(this).next('div.cloud').slideDown("slow");
    });

    $("a.help_button").mouseout(function() {
        $(this).next('div.cloud').slideUp('slow', function() {
            $(this).remove();
        });
    });

    $("a#user_button").addClass("wybrany")

    /**
    * Wybranie użytkowników jako kryterium wyszukiwania
    */
    $("a#user_button").click(function() {
        $("a#user_button").addClass("wybrany")
        $("a#gift_button").removeClass("wybrany")
        document.getElementById('q').value='1'
        return false;
    });

    /**
    * Wybranie prezentów jako kryterium wyszukiwania
    */
    $("a#gift_button").click(function() {
        $("a#user_button").removeClass("wybrany")
        $("a#gift_button").addClass("wybrany")
        document.getElementById('q').value='0'
        return false;
    })

    /**
    * Wysłanie formularza wyszukującego użytkowników / prezenty
    */
    $("a#find_button").click(function() {
        document.szukajForm.submit()
    })

    /**
    * Wyświetlanie "tu to kupisz"
    */
    $("div.buy_options a.buy_button").toggle(function(){
        $(this).parent("div.buy_options").addClass("bg");
        $(this).parent("div.buy_options").children("ul").slideDown();
        return false;
    }, function(){
        
        $(this).parent("div.buy_options").children("ul").slideUp('slow', function() {
            $(this).parent("div.buy_options").removeClass("bg");
        });
        return false;
    });
	
    /**
    * Pokaż więcej/Pokaż mniej prezentów
    */
    var dl=$("div#prezenty ul.gift_list").children("li").length;
    var wyswietl=6;
    var wyswietl_tmp=wyswietl
    ukryj_pokaz(dl, wyswietl_tmp);
    $("div.see_more a.more").live('click', function() {
        wyswietl_tmp=wyswietl_tmp+wyswietl;
        if (wyswietl_tmp>dl) {
            wyswietl_tmp=dl;
        }
        $("div#prezenty ul.gift_list").children("li:lt("+wyswietl_tmp+")").slideDown();
        return false;
    });
    $("div.see_more a.less").live('click', function() {
        wyswietl_tmp=wyswietl_tmp-wyswietl;
        if (wyswietl_tmp<wyswietl) {
            wyswietl_tmp=wyswietl;
        }
        $("div#prezenty ul.gift_list").children("li:gt("+(wyswietl_tmp-1)+")").slideUp();
        return false;
    });

    $("#register_form #submit").click(function(){
        if($('#register_form #nazwiskoValid span').hasClass('valid') &&
            $('#register_form #imieValid span').hasClass('valid') &&
            $('#register_form #emailValid span').hasClass('valid') &&
            $('#register_form #nickValid span').hasClass('valid')
        ){
            pass1 = $('#register_form #haslo').val();
            pass2 = $('#register_form #haslo2').val();
            nick = $('#register_form #nick').val();
            email = $('#register_form #email').val();

            comapre_passwords(pass1, pass2);

            $.ajax({
                async: false,
                url: "/pl/uzytkownicy/checknick/format/json",
                dataType: "json",
                data: ({nick : nick}),
                success: function(response){
                    if(response.retvalue==1){
                        $('#nickValid span').addClass('invalid');
                        $('#nickValid span').removeClass('valid');
                    }
                    else{
                        $('#nickValid span').addClass('valid');
                        $('#nickValid span').removeClass('invalid');
                    }
                }
            });
            if($('#register_form #nickValid span').hasClass('invalid'))
                $("#nickValid p").html(komunikaty.nick_juz_jest);

            $.ajax({
                async: false,
                url: "/pl/uzytkownicy/checkemail/format/json",
                dataType: "json",
                data: ({email : email}),
                success: function(response){
                    if(response.retvalue==1){
                        $('#emailValid span').addClass('invalid');
                        $('#emailValid span').removeClass('valid');
                    }
                    else{
                        $('#emailValid span').addClass('valid');
                        $('#emailValid span').removeClass('invalid');
                    }
                }
            });
            if($('#register_form #emailValid span').hasClass('invalid'))
                $("#emailValid p").html(komunikaty.email_juz_jest);

            if($('#register_form #nickValid span').hasClass('invalid') ||
                $('#register_form #hasloValid span').hasClass('invalid') ||
                $('#register_form #haslo2Valid span').hasClass('invalid') ||
                $('#register_form #emailValid span').hasClass('invalid'))
                return false;
        }
        else{
            return false;
        }
    });

    /**
    * Walidacja pola imie
    */
    $("#register_form #imie").keyup(function() {
        value = $(this).val();
        validate_name(value);
    });
    $("#register_form #imie").mouseup(function() {
        value = $(this).val();
        validate_name(value);
    });

    /**
    * Walidacja pola nazwisko
    */
    $("#register_form #nazwisko").keyup(function() {
        value = $(this).val();
        validate_surname(value);
    });
    $("#register_form #nazwisko").mouseup(function() {
        value = $(this).val();
        validate_surname(value);
    });

    /**
    * automatyczne tworzenie nicka
    */
    $("#register_form #nazwisko, #register_form #imie").keyup(function() {
        nazwisko = $("#nazwisko").val();
        nazwisko = nazwisko.toLowerCase();
        imie = $("#imie").val();
        imie = imie.toLowerCase();
        
        imie = imie.replaceAll('ł','l');
        imie = imie.replaceAll('ą','a');
        imie = imie.replaceAll('ś','s');
        imie = imie.replaceAll('ć','c');
        imie = imie.replaceAll('ź','z');
        imie = imie.replaceAll('ż','z');
        imie = imie.replaceAll('ó','o');
        imie = imie.replaceAll('ę','e');
        imie = imie.replaceAll(' ','_');
        nazwisko = nazwisko.replaceAll('ł','l');
        nazwisko = nazwisko.replaceAll('ą','a');
        nazwisko = nazwisko.replaceAll('ś','s');
        nazwisko = nazwisko.replaceAll('ć','c');
        nazwisko = nazwisko.replaceAll('ź','z');
        nazwisko = nazwisko.replaceAll('ż','z');
        nazwisko = nazwisko.replaceAll('ó','o');
        nazwisko = nazwisko.replaceAll('ę','e');
        nazwisko = nazwisko.replaceAll(' ','_');

        nick = imie+"_"+nazwisko;
        validate_nick(nick);
        $("#nick").val(nick);
    })
   
    /**
    * Walidacja pola nick
    */
    $("#register_form #nick").keyup(function() {
        nick = $(this).val();
        validate_nick(nick);
    });
    $("#register_form #nick").mouseup(function() {
        nick = $(this).val();
        validate_nick(nick);
    });

    /**
     * Walidacja pola haslo
     */
    $('#register_form #haslo').keyup(function() {
        value = $(this).val();
        validate_pass1(value);
    })
    $('#register_form #haslo').mouseup(function() {
        value = $(this).val();
        validate_pass1(value);
    })

    /**
    * Walidacja pola haslo2
    */
    $('#register_form #haslo2').keyup(function() {
        value = $(this).val();
        validate_pass2(value);
    })
    $('#register_form #haslo2').mouseup(function() {
        value = $(this).val();
        validate_pass2(value);
    })

    /**
     * Walidacja pola email
     */
    $('#register_form #email').keyup(function() {
        email = $(this).val();
        validate_email(email);
    });
    $('#register_form #email').mouseup(function() {
        email = $(this).val();
        validate_email(email);
    });

    /**
     * Edycja pól Prezentu
     */
    $('.editablePrezent').editInPlace({
        url: "/en/prezenty/edytujajax",
        params: "id=" + $('td.id').html(),
        field_type: "text",
        show_buttons: true,
        tooltip   : komunikaty.tooltip,
        indicator: komunikaty.indicator
    });

    $('div.id').hide()

    /**
     * Edycja pól Użytkownika
     */
    $('.editableUzytkownik').editInPlace({
        url: "/en/uzytkownicy/edytujajax",
        params: "id=" + $('.id').val(),
        field_type: "text",
        show_buttons: true,
        indicator: komunikaty.indicator
    });

    /**
     * Edycja pól Partnera
     */
    $('.editablePartner').editInPlace({
        url: "/en/partnerzy/edytujajax",
        params: "id=" + $('td.id').html(),
        field_type: "text",
        show_buttons: true,
        tooltip   : komunikaty.tooltip,
        indicator: komunikaty.indicator
    });

    /**
     * Edycja pól Taga
     */
    $('.editableTag').editInPlace({
        url: "/en/tagi/edytujajax",
        params: "id=" + $('td.id').html(),
        field_type: "text",
        show_buttons: true
    });

    /*    $('#powiadom_zmiana').click(function () {
            var oldValue = $('#powiadom_zmiana').val()
            if(oldValue == 1) {
                value = 0
            }
            else {
                value = 1
            }
    
            $.post('/en/uzytkownicy/edytujcheckboxajax/format/html', {
                id: $('div.id').html(),
                oldval: oldValue,
                value: value
            }, function(data) {
                alert(data)
            })
    
        })*/

    $('#powiadom_zmiana, #fb_fotoname_change, #fb_friends_change').click(function() {
        name = $(this).attr('name');
        checked = $(this).attr('checked');
        button = $(this);

        if(checked==true) {
            checkedVal = 1;
        }
        else {
            checkedVal = 0;
        }

        $.post('/en/uzytkownicy/edytujcheckboxajax/format/html', {
            id: $('input.id').val(),
            value: checkedVal,
            name: name
        }, function(data) {
            $('div.powiadom_zmianaOdp').html(data);
            if(name=='fb_friends'){
                button.parent().parent().hide();
                button.parent().parent().prev().hide();
            }
        })
    })

    $('.wybor_nazwisko_nick').click(function() {
        name = $(this).attr('name');
        checkedVal = $(this).attr('value');

        $.post('/en/uzytkownicy/edytujcheckboxajax/format/html', {
            id: $('input.id').val(),
            value: checkedVal,
            name: name
        }, function(data) {
            $('div.powiadom_zmianaOdp').html(data)
        })
    })

    $('#dodaj_prezent').live('submit', function() {
        checked = $('#fb_check:checked').length;
        if(checked==1) {
            checked = 1;
        } else {
            checked = 0;
        }
        
        $.post('/en/prezenty/dodaj/format/html', {
            wlasciciel: $("#wlasciciel").val(),
            nazwa: $("#nazwa").val(),
            www: $("#www").val(),
            kolejnosc: $("#kolejnosc").val(),
            prywatny: $("#prywatny").val(),
            usuniety: $("#usuniety").val(),
            opis: $("#opis").val(),
            onfire: $("#onfire").val(),
            foto_nowe: $("#foto_nowe").val(),
            foto_stare: $("#foto_stare").val(),
            foto_id: $("#foto_id").val(),
            foto_podpowiedziane: $("#foto_podpowiedziane").val(),
            foto_www: $("#foto_www").val(),
            checked: checked
        }, function(data) {
            $("#dodaj_prezent_form").hide();

            if($('#dodaj_prezent').hasClass('edit')) {
                msg(komunikaty.prezent_zmieniony);
            } else {
                $('#najnowsze').trigger('click');
                ukryj_pokaz(dl, wyswietl_tmp);
                msg(data);
            }
            if($("#wymarzone").length!=0) {
                $("#wymarzone").trigger('click');
            }
        });

        return false;
    });

    $('#podpowiedzObrazek').hide()
    $('#podpowiedz').live('click', function() {
        $('#podpowiedzObrazek').fadeIn('slow')
        return false;
    })

    $('#zamknijpodpowiedzObrazek').live('click', function() {
        $('#podpowiedzObrazek').fadeOut('slow')
        return false;
    })

    $('#nazwa').blur(function() { 
        podpowiedz_obrazek();
        return false;
    })

    $('#nazwaObrazkaEd').change(function() {
        $.post('/en/prezenty/szukajobrazka/format/html', {
            nazwa: $('#nazwaObrazkaEd').val()
        }, function(data) {
            $('#nazwaObrazkaEdOdp').html(data)
        })
        return false
    })

    $('#edytujObrazek').hide()

    $('#zmienObrazekLink').click(function () {
        $('#edytujObrazek').fadeIn('slow')
    })

    $('#zamknijEdytujObrazekLink').click(function() {
        $('#edytujObrazek').fadeOut('slow')
    })

    $('.nowe_foto').live('click', function() {
        $("#photos_field ul li, #photos_field_u ul li").removeClass('wybrany');
        $(this).parent().parent().addClass('wybrany');
        link = $(this).attr('href');

        $("#foto_nowe").val(link);
        $("#foto_podpowiedziane").val('');
        $("#foto_www").val('');
        return false
    });

    $('.www_foto').live('click', function() {
        $("#photos_field ul li, #photos_field_u ul li").removeClass('wybrany');
        $(this).parent().parent().addClass('wybrany');
        link = $(this).attr('href');
        $("input#foto_www").val(link);
        $("#foto_podpowiedziane").val('');
        $("#foto_nowe").val('');
        return false;
    });
    
    $('.proponowany').live('click', function() {
        $('#photos_field ul li, #photos_field_u ul li').removeClass('wybrany');
        $(this).parent().parent().addClass('wybrany');
        link = $(this).attr('href');
        $("#foto_nowe").val('');
        $("#foto_podpowiedziane").val(link);
        $("#foto_www").val('');
        return false;
    })

    $('#dodaj_tag').submit(function () {
        $.post( '/en/tagi/dodaj/format/html', {
            nazwa: $('#tagNazwa').val(),
            data_przypisania: $('#data_przypisania').val()
        }, function(data) {
            $('div.user_tags_list').prepend(data);
            $('#add_tag_form').fadeOut('slow');
            msg(komunikaty.dodano_liste);
        });

        return false;
    });

    $('.dodajIstnLink').click(function () {
        link = $(this).attr('href')
        if(confirm(komunikaty.dodaj_tag_do_prezentu)) {
            $.post( link, {

                }, function(data) {
                    msg(data)
                })

            $(this).fadeOut('slow')
        }
        else {
            msg(komunikaty.tag_neg)
        }
        return false
    });

    $('#zmienAvatar').click(function() {
        link = $(this).attr('href')
        
        $.post( link, {
            id: $(".id").html()
        }, function(data) {
            })
        return false
    })

    $('#zmienZdjecie').click(function() {
        link = $(this).attr('href')

        $.post( link, {
            id: $(".id").html()
        }, function(data) {
            })
        return false
    })

    $('.odtagujLink').click(function() {
        link = $(this).attr('href')
        if(confirm(komunikaty.otaguj_prezent)) {
            $.post( link, {

                }, function(data) {
                    msg(data)
                })

            $(this).fadeOut('slow')
        }
        else {
            msg(komunikaty.otaguj_neg)
        }
        return false
    })

    $('.del').click(function() {
        link = $(this).attr('href')
        if(confirm(komunikaty.usun)) {
            window.location = link
        }
        return false;
    })

    $('#tagi').hide()
    
    $('.otaguj').click(function() {
        $('#tagi').fadeIn('slow')
        $('#dodajTagOdp').fadeOut('fast')
        $('#dodajTagForm').fadeIn('slow')
        $(this).fadeOut('slow')
        
        return false;
    });

    $('#zamknijOtagujLink').click(function() {
        $('#tagi').fadeOut('slow')
        $('.otaguj').fadeIn('slow')
        return false
    });

    /**
     * AJAXowe wysyłanie zaproszenia
     */
    $('a.zapros').click(function() {
        link = $(this).attr('href')
        imie = $(this).parent().parent().children('.imie').html()

        if(confirm(komunikaty.zapros)) {
            $.post( link, {
                
                }, function(data) {
                    msg(data);
                });

            $(this).fadeOut("slow")
        }
        else {
            msg(komunikaty.zaproszenie_neg);
        }
        return false;

    });

    $('.dajePrezent').click(function() {
        link = $(this).attr('href')
        id = $(this).parent().parent().children('.id').html()
        if(confirm(komunikaty.daj_prezent)) {
            $.post( link, {

                }, function(data) {
                    msg(data)
                })

            $(this).fadeOut('slow')
        }
        else {
            msg(komunikaty.prezent_neg)
        }
        return false
    });

    $('#zrzutkaPrezentForm').hide();
    $('#zamknijZrzutkaLink').hide();

    $('.zrzucamPrezent').click(function () {
        link = $(this).attr('href')
        id = $(this).parent().parent().children('.id').html()

        $('#zrzutkaPrezentForm').fadeIn('slow')
        $('#zamknijZrzutkaLink').fadeIn('slow')
        
        return false
    })

    $('#zrzutka_form').submit(function() {
        $.post( '/en/prezenty/zrzucam/format/html', {
            kwota: $("#kwota").val(),
            id: $('#prezent_id').val()
        }, function(data) {
            msg(data)
        });

        $('#zrzutkaPrezentForm').fadeOut('slow')
        $('#zamknijZrzutkaLink').fadeOut('slow')

        return false;
    });

    $('#zamknijZrzutkaLink').click(function() {
        $('#zrzutkaPrezentForm').fadeOut('slow')
        $(this).fadeOut('slow')
        $('#zrzutkaOdp').html()
        return false;
    });

    $('.usunZnaj').click(function() {
        link = $(this).attr('href')
        if(confirm(komunikaty.usunac_znajomego)) {
            $.post( link, {

                }, function(data) {
                    msg(data);
                });

            $(this).parent().parent().fadeOut('slow')
        }
        else {
            msg(komunikaty.usun_znajomego_neg);
        }
        return false;
    });

    $('.usunPartnera').click(function() {
        link = $(this).attr('href')
        if(confirm(komunikaty.usunac_partnera)) {
            $.post( link, {

                }, function(data) {
                    msg(data);
                });
                
            $(this).parent().parent().fadeOut('slow')
        }
        else {
            msg(komunikaty.usun_partnera_neg)
        }
        return false;
    });

    $('.usunPrezent').live('click', function() {
        link = $(this).attr('href')
        if(confirm(komunikaty.usunac_prezent)) {
            $.post( link, {}, function(data) {
                msg(data);
                window.location = '/prezenty/moje';
            });
            $(this).parent().parent().fadeOut('slow')
            
        }
        else {
            msg(komunikaty.usun_prezent_neg)
        }
        return false;
    });

    $('.usunTag').click(function() {
        link = $(this).attr('href')
        if(confirm(komunikaty.usunac_tag)) {
            $.post( link, {}, function(data) {
                msg(data);
            });
            $(this).parent().parent().fadeOut('slow')
        }
        else {
            msg(komunikaty.usun_tag_neg)
        }
        return false;
    });

    $('#ostatnie, #najnowsze, #wszystkie').click(function() {
        link = $(this).attr('href')
        button = $(this);
        $.post(link, {}, function(data) {
            $('#prezenty_contener').fadeOut();
            $('#prezenty_contener').html(data);
            ukryj_pokaz(dl,wyswietl_tmp);
            $('#prezenty_contener').fadeIn();
            $('.option_navi a').removeClass('active');
            button.addClass('active');
        });
        return false;
    });

    $('.send_answer, .send_answer_to').live('click', function() {
        link = $(this).attr('href');
        tresc = $(this).prev().prev().val();
        checked = $('#fb_check:checked').length;
        if(checked==2) {
            checked = 1;
        } else {
            checked = 0;
        }
        
        button = $(this).parent().parent().parent().parent();
        thisb = $(this);

        if(tresc=='') {
            msg(komunikaty.komentarz_pusty);
            return false;
        }
        if(thisb.hasClass('send_answer_to')) {
            $.post(link, {
                tresc: tresc,
                small: 1,
                checked: checked
            }, function(data) {
                thisb.parent().parent().parent().parent().parent().after(data)
                thisb.parent().slideUp();
                msg(komunikaty.komentarz_dodano);
            });
        } else {
            $.post(link, {
                tresc: tresc,
                small: 0,
                checked: checked
            }, function(data) {
                $('.comments').prepend(data);
                msg(komunikaty.komentarz_dodano);
            });
        }
        return false;
    });

    $('.del_comment').live('click', function() {
        link = $(this).attr('href')

        if(confirm(komunikaty.usunac_komentarz)) {
            $.post( link, {
                }, function(data) {
                    $('#del_comment_answer').html(data);
                });
            $(this).parent().parent().parent().parent().fadeOut('slow');
        }
        else {
            $('#del_comment_answer').html(komunikaty.usun_komentarz_neg)
        }
        return false;
    });

    $('.oznacz_zdobyty').live('click', function() {
        button = $(this)
        link = $(this).attr('href')
        $.post(link, {}, function() {
            $('a.notvisible').show();
            $('a.notvisible').removeClass('notvisible');
            if(button.parent().hasClass('przyciski2')) {
                button.parent().removeClass('przyciski2');
            } else {
                button.parent().addClass('przyciski2');
            }
            button.addClass('notvisible');
            if(button.parent().hasClass('dozdobycia') || button.parent().hasClass('zdobyty')) {
                button.parent().parent().parent().fadeOut();
            }
            button.hide();
        });
        return false;
    });

    $('a.add_list').live('click', function() {
        button = $(this);
        link = $(this).attr('href');
        tag = $(this).html();
        $.post(link, {}, function(data) {
            if(data=='Duplicate error' || data=='Handle exception'){ 
                msg(komunikaty.przypisanie_do_listy_neg);
            }
            else if(data=='Error'){ 
                msg(komunikaty.blad);
            }
            else{ 
                $('.present_tags em').after(' '+data+' ');
                msg(komunikaty.przypisanie_do_listy);
            }
        });
        return false;
    });

    $('.present_tags a').live('click', function() {
        button = $(this);
        link = $(this).attr('href');
        $.post(link, {}, function(data) {
            button.fadeOut('slow', function(){
                msg(komunikaty.usuniecie_z_listy)
            });
        });

        return false;
    });

    $('.add_link').live('click', function() {
        button = $(this);
        link = $(this).attr('href');
        $.getJSON(link, {}, function(data) {
            if(data==0){ 
                msg(komunikaty.nie_sklonowano);
            }
            else{
                msg(data.msg);
                button.fadeOut('slow');
            }
            if(data.msg=='Produkt dodany do Twojej listy') {
                button.fadeOut('slow');
            }
        });
        
        return false;
    });

    /**
     * lista prezentów powiązanych z danym tagiem
     */
    $('a.switch_list').click(function(){
        button = $(this);
        link = $(this).attr('href');
        $.post(link, {}, function(data) {
            $('div.user_gifts').html(data);
            measure_height();
        });

        return false;
    });

    /**
     * lista wszystkich wymarzonych prezentów
     */
    $('#user_tags_home').click(function(){
        $('.user_tags_list').animate({
            marginLeft: '0px'
        }, 1500);
        return false;
    });

    /**
     * przełączanie podwidoków listy prezentów zdobytych i wymarzonych
     */
    $('#sub #zdobyte, #sub #wymarzone, #sub #zdobytyprzez, #sub #wymarzonyprzez').click(function(){
        button = $(this);
        link = $(this).attr('href');
        $(".action_button").hide();
        if(!$(this).hasClass('small_return')) {
            $.post(link, {}, function(data) {
                $('div.user_gifts').html(data);
                $('#sub li').removeClass('active');
                changeLastBreadcrumb(button.attr('id'));
                renderSifr();
                button.parent().attr('class', "active");
            });
        } else {
            $.post(link, { 
                small_return: 1
            }, function(data) {
                $('div.sub_wrapper').html(data);
                $('#sub li').removeClass('active');
                renderSifr();
                button.parent().attr('class', "active");
            });
        }
        
        measure_height();
        return false;
    });
    $("#sub #znajomi").click(function() {
        $(".action_button").show();
        button = $(this);
        link = $(this).attr('href');
        $(".action_button").show();
        if(!$(this).hasClass('small_return')) {
            $.post(link, {}, function(data) {
                $('div.user_gifts').html(data);
                $('#sub li').removeClass('active');
                changeLastBreadcrumb(button.attr('id'));
                renderSifr();
                button.parent().attr('class', "active");
            });
        } else {
            $.post(link, {
                small_return: 1
            }, function(data) {
                $('div.sub_wrapper').html(data);
                $('#sub li').removeClass('active');
                renderSifr();
                button.parent().attr('class', "active");
            });
        }

        measure_height();
        return false;
    })

    $('#add_tag_form').hide();
    $('#add_tag').click(function(){
        $('#add_tag_form').slideToggle();
        return false;
    })

    $('.komponuj').live('click', function() {
        var href = $(this).attr('href');
        $.post(href, {}, function(data) {
            $("#komponuj").html(data);
            $("#komponuj").show();
        });
        return false;
    })

    /**
     * dodaj użytkownika do listy darczyńców danego prezentu
     */
    $('a.add_dajacy').click(function(){
        button = $(this);
        link = $(this).attr('href');
        $.post(link, {}, function(data) {
            if(data!=''){
                msg(komunikaty.lista_dodano);
                $('li.puste_lista_info').remove();
                button.hide();
                $('.giving_list').append(data);
                $("#znajomi").trigger('click');
                $('.del_from_list').show();
            }
            else{
                msg(komunikaty.lista_dodano_neg);
            }
        });
        return false;
    });
    $(".del_from_list").live('click', function() {
        link = $(this).attr('href');
        button = $(this);
        if(confirm(komunikaty.usun_z_listy_ofiarowadcow)) {
            $.post(link, {}, function(data) {
                button.hide();
                $('.add_dajacy').show();
                $("#znajomi").trigger('click');
            });
        }
        return false;
    })

    /**
     * aktywujemy danego partnera (dodajemy do bazy z 1)
     */
    $(".aktywuj").click(function() {
        target = $(this);
        $.post($(this).attr('href'), {}, function(data) {
            target.parent().parent().children(".partner").html(komunikaty.aktywny_1);
            target.fadeOut();
        })
        return false;
    })

    $("#loader").bind('ajaxSend', function() { 
        $(this).show();
    }).bind('ajaxComplete', function() {
        $(this).hide();

        mine_hover();
        mine_sortable();
    });

    $('.reply').live('click', function() { 
        $(this).next('.reply_content').slideToggle();
        return false;
    })

    $('.why_worth_show').click(function() {
        $("#user_events_container, #cloud_container").hide();
        $("#why_worth").fadeIn();
        renderSifr();
        return false;
    })
    $('div .back_why').click(function() {
        $("#why_worth").hide();
        $("#user_events_container, #cloud_container").fadeIn();
        return false;
    })

    mine_hover();
    mine_sortable();

    $('.prev_slide').click(function() {
        currentMargin = $('.user_tags_list').css('margin-left');
        move = parseInt(currentMargin)-55;
        $('.user_tags_list').animate({
            marginLeft: move+'px'
        }, 500);
        return false;
    })
    $('.next_slide').click(function() {
        currentMargin = $('.user_tags_list').css('margin-left');
        if(parseInt(currentMargin)<0) {
            move = parseInt(currentMargin)+55;
            $('.user_tags_list').animate({
                marginLeft: move
            }, 500);
        }
        return false;
    })

    $('.breadcrumb li:first').addClass('first');
    $("a.box").colorbox({
        transition:"fade"
    });

    $(".formularz_wysylania").click(function() { 
        $("#wyslij_wiadomosc").slideToggle();
        wyczysc_formularz_wysylania();
        return false;
    });

    $("#fb_connect_form #nick").keyup(function(){
        nick = $("#fb_connect_form #nick").val();
        $.getJSON('/pl/uzytkownicy/checknick/format/json', {
            nick: nick
        }, function(data) {
            if(data.retvalue==1){
                alert('nick już istnieje');
            }
            return false;
        });
    });

    $('#join_account').click(function(){
        span = $(this).next('span.join_account');
        span.slideToggle("slow");
        $("#fb_connect_form #nick").parent().slideToggle("slow");
        $(this).toggleClass("active");

        return false;
    })

    $("#fb_connect_form #submit").click(function(){
        action = $('#fb_connect_form').attr('action')+'/format/json';
        if($('#fb_connect_form #nick').parent().css('display')!='none' && $('#fb_connect_form #nick').val()==''){
            alert("Podanie nicka jest obowiązkowe.");
            return false;
        }
        if($('#fb_connect_form #nick').parent().css('display')=='none' && $('#fb_connect_form #username').val()=='' && $('#fb_connect_form #password').val()==''){
            alert("Pola login i hasło są wymagana do połączenia kont.");
            return false;
        }
        
        $.getJSON(action, {
            username: $('#fb_connect_form #username').val(),
            password: $('#fb_connect_form #password').val(),
            nick: $('#fb_connect_form #nick').val(),
            fb_user: $('#fb_connect_form #fb_user').val(),
            fb_friends: $('#fb_friends').attr('checked'),
            fb_fotoname: $('#fb_fotoname').attr('checked')
        }, function(data) {
            if(data.error){
                alert("Błędny login lub hasło.");
            }
            else{
                if(data.fb_permission_email==0){
                    FB.Connect.showPermissionDialog("email", function(response) {
                        window.location = '/'+data.lang+'/uzytkownicy/edytujprofil';
                    });
                }
                else{
                    window.location = '/'+data.lang+'/uzytkownicy/edytujprofil';
                }
            }
        });
        return false;
    });

    //    measure_height();
});

String.prototype.replaceAll = function(
    strTarget,
    strSubString
    ){
    var strText = this;
    var intIndexOfMatch = strText.indexOf( strTarget );

    while (intIndexOfMatch != -1){
        strText = strText.replace( strTarget, strSubString )
        intIndexOfMatch = strText.indexOf( strTarget );
    }
    return( strText );
}

function validate(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var address = email;
    if(reg.test(address) == false) {
        return false;
    }
    return true;
}

function mine_sortable() {
    $('.mine_list').sortable({
        cursor: 'move',
        handle: '.move',
        axis: 'y',
        stop: function(event,ui) {
            array = $('.mine_list').sortable('serialize')

            $.get('/pl/prezenty/sortowanie/format/html', {
                prezenty: array
            })
        }
    });
}

function mine_hover() {
    $('.mine_list li').hover(function() {
        $('.usunPrezent, .oznacz_zdobyty, .edit_prezent').hide();
        $('.move').hide();
        $(this).children('.description').children('.przyciski').children('.usunPrezent, .oznacz_zdobyty, .edit_prezent').fadeIn();
        $(this).children('.description').children('.dozdobycia,.zdobyty').children('.oznacz_zdobyty').fadeIn();
        $(this).children('.move').fadeIn();
    }, function() {
        $(this).children('.description').children('.przyciski').children('.usunPrezent, .oznacz_zdobyty, .edit_prezent').hide();
        $(this).children('.description').children('.dozdobycia,.zdobyty').children('.oznacz_zdobyty').hide();
        $(this).children('.move').hide();
    })
}

function widthPopup() {
    width = $("#popup_alert").width();
    $("#popup_alert").css('marginLeft',-(width+16)/2);
}

function podpowiedz_obrazek() {
    $.post('/en/prezenty/szukajobrazka/format/html', {
        nazwa: $('#nazwa').val()
    }, function(data) {
        $("#photos_field ul").hide();
        $("#photos_field ul").html(data);
        $("#photos_field ul").fadeIn();
    });
}

function wyczysc_formularz_prezentu() {
    $('#photos_field li, #photos_field_u li').remove();
    $('#opis').val(komunikaty.opis_field);
    $('#dodaj_prezent').removeClass();
    $('#www').val(komunikaty.www_field);
    $('#www').val(komunikaty.www_field);
    $("#foto_nowe,#foto_stare,#foto_podpowiedziane,#foto_www").val('');
    $("#info").remove();
}

function valid(element) {
    $(element+' span').addClass('valid');
    $(element+' span').removeClass('invalid');
    $(element+' p').html('');
}

function invalid(element) {
    $(element+' span').addClass('invalid');
    $(element+' span').removeClass('valid');
}

function renderSifr() {
    var font = {
        src: '/_p/flash/font.swf'
    };
    sIFR.activate(font);
    sIFR.replace (font, {
        selector: 'h3.sifr',
        css: {
            '.sIFR-root': {
                'color': '#F74A17',
                'font-weight' : 'bold'
            }
        },
        wmode: 'transparent'
    });
}


function msg(msg) { 
    $("#info_alert span").html(msg);
    $("#info_alert").fadeIn();
    setTimeout(function() { 
        close_messages()
    }, 2000);
}

function close_messages() {
    $("#info_alert").fadeOut("slow");
}

function measure_height() {
    var sub = $("#sub").height();
    var main = $("#main").height();
    if(sub>main) {
        $("#main").height((sub+25)+"px")
    }
}

function wyczysc_formularz_wysylania() {
    $("#temat").val('');
    $("#tresc").val('');
}

function changeLastBreadcrumb(label) {
    $('.breadcrumb .lastitem').html(label);
}

function validate_name(value){
    if(!value){
        invalid('#imieValid');
        $("#imieValid p").html(komunikaty.imie_puste);
    }
    else {
        var reg = /^[A-Za-zĄąĘęŁłÓóŚśŻżŹźńŃ \-]+$/;
        if (!reg.test(value)){
            invalid('#imieValid');
            $("#nazwiskoValid p").html(komunikaty.nazwisko_bledne);
        }
        else {
            valid('#imieValid');
            $("#imieValid span").removeClass("invalid");
            $("#imieValid span").addClass("valid");
        }
    }
}
function validate_surname(value){
    if(!value){
        invalid('#nazwiskoValid');
        $("#nazwiskoValid p").html(komunikaty.nazwisko_puste);
    }
    else {
        var reg = /^[A-Za-zĄąĘęŁłÓóŚśŻżŹźńŃ \-]+$/;
        if (!reg.test(value)){
            invalid('#nazwiskoValid');
            $("#nazwiskoValid p").html(komunikaty.nazwisko_bledne);
        }
        else {
            valid('#nazwiskoValid');
        }
    }
}
function validate_nick(value){
    if(!value){
        invalid("#nickValid");
        $("#nickValid p").html(komunikaty.nick_pusty);
    }
    else {
        var reg = /^[A-Za-zĄąĘęŁłÓóŚśŻżŹź0-9_\-]+$/;
        if (!reg.test(value)){
            invalid("#nickValid");
            $("#nickValid p").html(komunikaty.nick_bledny);
        }
        else {
            valid("#nickValid");
        }
    }
}
function validate_pass1(value){
    if(value.length > 0) {
        if(value.length < 4) {
            invalid("#hasloValid");
            $("#hasloValid p").html(komunikaty.haslo_krotkie);
        }
        else if(value.length > 30) {
            invalid("#hasloValid");
            $("#hasloValid p").html(komunikaty.haslo_dlugie);
        }
        else{
            valid("#hasloValid");
        }
    }
    else {
        invalid("#hasloValid");
        $("#nickValid p").html(komunikaty.haslo_puste);
    }
}
function validate_pass2(value){
    if(value.length > 0) {
        if(value.length < 4) {
            invalid("#haslo2Valid");
            $("#haslo2Valid p").html(komunikaty.haslo2_krotkie);
        }
        else if(value.length > 30) {
            invalid("#haslo2Valid");
            $("#haslo2Valid p").html(komunikaty.haslo2_dlugie);
        }
        else{
            valid("#haslo2Valid");
        }
    }
    else {
        invalid("#haslo2Valid");
        $("#haslo2Valid p").html(komunikaty.haslo2_puste);
    }
}
function comapre_passwords(value1, value2){
    if(value1!='' && value2!=''){
        if(value1 == value2) {
            valid("#hasloValid");
            valid("#haslo2Valid");
        }
        else{
            valid("#hasloValid");
            invalid("#haslo2Valid");
            $("#haslo2Valid p").html(komunikaty.pola_rozniasie);
        }
    }
}
function validate_email(email){
    if(value.length > 0) {
        result = validate(email);

        if(result) {
            $.post('/en/uzytkownicy/waliduj/format/html', {
                wartosc: email,
                pole: 'email'
            }, function(data) {
                if(data) {
                    if(data=='0') {
                        invalid("#emailValid");
                        $("#emailValid p").html(komunikaty.email_zajety);
                    }
                    else {
                        valid('#emailValid');
                    }
                }
            })
        }
        else {
            invalid("#emailValid");
            $("#emailValid p").html(komunikaty.email_bledny);
        }
    }
    else{
        invalid("#emailValid");
    }
}

function ukryj_pokaz(dl,wyswietl_tmp) {
    dl = $("div#prezenty ul.gift_list").children("li").length;
    $("div#prezenty ul.gift_list").children("li").hide();
    $("div#prezenty ul.gift_list").children("li:lt("+wyswietl_tmp+")").show();
}
