$(document).ready(function() {
    $('.pla a').hide();
    
    $('input, textarea').focus(
        function() {
            $(this).addClass('focus');
        }
        );

    $('input').blur(
        function() {
            $(this).removeClass('focus');
        }
        );

    $("#masa").blur(function() {
        masa = $(this).val();
        masa = coma_to_dots(masa)
        $(this).val(masa);
    })

    $('#kpo_m input, #kpo_m textarea').focus(
        function() {
            $(this).addClass('focus');
        }
        );

    $('#kpo_m input, #kpo_m textarea').blur(
        function() {
            $(this).removeClass('focus');
        }
        );

    $(".del").live('click', function() {
        button= $(this);
        title = $(this).attr('title');
        $(".del_dialog").children('.del_text').text(title);
        $(".del_dialog").dialog('open');
        return false;
    });

    $(".del2").live('click', function() {
        button= $(this);
        title = $(this).attr('title');
        $(".del_dialog2").children('.del_text').text(title);
        $(".del_dialog2").dialog('open');
        return false;
    });

    $('.tools .mark_star').click(function() {
        $('.head').toggleClass('star');
    });

    $("#nazwa_pos").focus(function() { 
        clearfields("pos");
    })
    $("#nazwa_prz").focus(function() { 
        clearfields("prz");
    })
    $("#nazwa_pro").focus(function() { 
        clearfields("pro");
    })
    $('#nazwa_pos').result(function(event, data, formatted) { 
        insert(data, "pos");
    });
    $('#nazwa_prz').result(function(event, data, formatted) { 
        insert(data, "prz");
    });
    $('#nazwa_pro').result(function(event, data, formatted) { 
        insert(data, "pro");
    });
    $("#nazwa_pos, #nazwa_prz, #nazwa_pro").autocomplete("/firmy/wszyscy", {
        width: 310,
        autoFill: false,
        cacheLength: 1,
        formatItem: formatItem,
        formatResult: formatResult
    });
    
    $("#kontrahent_search").autocomplete("/firmy/wszyscy", {
        width: 310,
        autoFill: false,
        cacheLength: 1,
        formatItem: formatItem,
        formatResult: formatResult
    }).result(function(event, data) {
        $("#kontrahent").val(data[6]);
        $("#kontrahent_data").html(data[0]+"<br />"+data[3]+"<br />"+data[5]+" "+data[4]+"<br />NIP: "+data[1]);
    });
    
    $("#kontrahent_search2").autocomplete("/firmy/wszyscy", {
        width: 310,
        autoFill: false,
        cacheLength: 1,
        formatItem: formatItem,
        formatResult: formatResult
    }).result(function(event, data) {
        var pole = '<input type="hidden" name="kupujacy[]" value="'+data[6]+'" />';
        $("#kontrahent_data").append("<span>"+data[0]+" <a href='#' class='usun_kupujacego'>X</a>; "+pole+"</span>");
        $('#kontrahent_search2').val("");
        $('#kontrahent_search2').focus();
    });
    
    $('.usun_kupujacego').live('click', function() {
        $(this).parent().remove();
        return false;
    });
    $('.usun_automator').live('click', function() {
        $(this).parent().remove();
        link= $(this).attr('href');
        $.post(link, {}, function(data){});
        return false;
    })

    $("#tagi_w").autocomplete('/tagi/allinvoiceautocomplete', {
        matchContains: true,
        minChars: 1
    });

    $("#tagi_w_kpo").autocomplete('/tagi/allkpoautocomplete', {
        matchContains: true,
        minChars: 1
    });

    $("#status_s").focus(function() {
        val = $("#status_s").val();
        if(val!='') {
            $("#status_s").val("");
            $("#miesiac_s").val("");
            $("#rok_s").val("");
        //            sendform();
        }
    });
    $("#miesiac_x").autocomplete('/default/kpo/datas', {
        width: 105,
        autoFill: false,
        cacheLength: 1,
        formatItem: function (row) {
            returner = row[2] +" "+row[3];
            return returner;
        },
        formatResult: function(row) {
            $("#miesiac_w").val();
            $("#rok_w").val();
            return row[2]+" "+row[3];
        },
        formatMatch: function(row) {
            return row.name + " " + row.to;
        }
    }).result(function(event, data) {
        $("#miesiac_w").val(data[0]);
        $("#rok_w").val(data[1]);
    //        sendform();
    });
    $("#status_s").autocomplete('/default/kpo/datas', {
        width: 105,
        autoFill: false,
        cacheLength: 1,
        formatItem: function (row) {
            returner = row[2] +" "+row[3];
            return returner;
        },
        formatResult: function(row) {
            $("#miesiac_s").val();
            $("#rok_s").val();
            return row[2]+" "+row[3];
        },
        formatMatch: function(row) {
            return row.name + " " + row.to;
        }
    }).result(function(event, data) {
        $("#miesiac_s").val(data[0]);
        $("#rok_s").val(data[1]);
    //        sendform2();
    });
    $("#wystawiona_w").autocomplete('/default/kpo/datas', {
        width: 105,
        autoFill: false,
        cacheLength: 1,
        formatItem: function (row) {
            returner = row[2] +" "+row[3];
            return returner;
        },
        formatResult: function(row) {
            $("#miesiac_w").val();
            $("#rok_w").val();
            return row[2]+" "+row[3];
        },
        formatMatch: function(row) {
            return row.name + " " + row.to;
        }
    }).result(function(event, data) {
        $("#miesiac_w").val(data[0]);
        $("#rok_w").val(data[1]);
    //        sendform2();
    });

    $("#nazwa_pos_w, #nazwa_prz_w, #nazwa_pro_w, #kontrahent_w").autocomplete("/firmy/wszyscy", {
        width: 310,
        autoFill: false,
        cacheLength: 1,
        formatItem: formatItem,
        formatResult: formatResult
    });
    $("#regon_pos, #regon_prz, #regon_pro").autocomplete("/firmy/wszyscy", {
        width: 310,
        autoFill: false,
        cacheLength: 1,
        formatItem: function (row) {
            returner = "REGON:" +  row[2] +", "+row[0]+", NIP " + row[1];
            return returner;
        },
        formatResult: function(row) { 
            return row[2];
        }
    });
    $("#nip_pos, #nip_prz, #nip_pro").autocomplete("/firmy/wszyscy", {
        width: 310,
        autoFill: false,
        cacheLength: 1,
        formatItem: function (row) {
            returner = "NIP:" +  row[1] +", "+row[0];
            if(row[2]!='') {
                returner += ", REGON " + row[2]
            }
            return returner;
        },
        formatResult: function(row) { 
            return row[1];
        }
    });

    $("#kpo_m #kod, #rodzaj").autocomplete("/odpady/wszystkie", {
        width: 810,
        autoFill: false,
        formatItem: formatItemOdpad,
        formatResult: function(row) { 
            return row[0];
        }
    });
    $("#kod_odpadu, #nazwa_odpadu").autocomplete("/odpady/wszystkie", {
        width: 810,
        autoFill: false,
        formatItem: formatItemOdpad,
        formatResult: function(row) {
            return row[0];
        }
    }).result(function(event, data, formatted) {
        $("#kod_odpadu").val(data[0]);
        $("#nazwa_odpadu").val(data[1]);
    });
    search_towar();
    
    $('#kpo_m #kod, #rodzaj').result(function(event, data, formatted) {
        insertodpad(data);
    });
    $("#kpo_m #kod, #rodzaj").focus(function() {
        clearodpad();
    });

    $("#data_w").datepicker();
    $("#data").datepicker();
    $("#data_wystawienia_d").datepicker();
    
    $("#widgetField").hover(function() {
        $(this).addClass("hand");
    }, function() {
        $(this).removeClass("hand");
    })
    $("#rok").result(function(event, data, formatted) {
        if($("#rok").val()!="") {
            $("#data").dpSetSelected('01/01/2007');
        }
    });
    $("#rok").focus(function() { 
        $("#rok").val("");
        $("#data").val("");
    });
    
    $(".n_input a").hover(function() {
        rel = $(this).attr("rel");
        $("#"+rel).fadeIn("slow");
    }, function() {
        rel = $(this).attr("rel");
        $("#"+rel).fadeOut("slow");
    })

    $(".new_window_pos").click(function() {
        $(".fly_pos").slideDown("slow");
        return false;
    });
    $(".new_window_pro").click(function() {
        $(".fly_pro").slideDown("slow");
        return false;
    });
    $(".new_window_prz").click(function() {
        $(".fly_prz").slideDown("slow");
        return false;
    });

    $(".close_window").click(function() {
        $(".fly_"+$(this).attr("rel"), window.top.document).slideUp("slow");
    });

    $(".s_mail a, .s_note a").click(function() {
        $(this).parent().parent().slideUp("slow");
        return false;
    });

    $("#loader").bind('ajaxSend', function() {
        $(this).show();
    }).bind('ajaxComplete', function() {
        $(this).hide();
    });
    
    $("#oplacony_but, #nieoplacony_but, #przeterminowany_but").click(function() {
        name = $(this).attr('id').slice(0,-4);
        $("#oplacony_but, #nieoplacony_but, #przeterminowany_but").not("#"+name+"_but").addClass('opacity');
        $("#oplacony_w, #nieoplacony_w, #przeterminowany_w").not("#"+name+"_w").val(0);
        $(this).toggleClass('opacity');
        var current = $("#"+name+"_w").val();
        if(current==1) {
            $("#"+name+"_w").val('0');
        } else {
            $("#"+name+"_w").val('1');
        }
        return false;
    })


    $(".sub li:first").addClass("first");
    $(".sub li:last").addClass("last");
    id_sub = $(".sub").attr('id');
    $(".sub li."+id_sub+" a").addClass("active");

    id_main = $('.menu').attr('id');
    $(".menu li."+id_main+" a").addClass("active");

    $(".printer").live('click', function() {
        window.print();
        return false;
    });

    $(".s_mail_w").click(function() {
        $(".s_mail").slideToggle("slow");
        $("#kpo_m_send").slideDown("slow");
        $('.msg_field').html("Podaj adres na jaki chcesz wysłać kartę:");
        $("#s_mail").val("");
        return false;
    });

    function updateNote(id) {
        $.post("/default/note/list/id/"+id, {},
            function(data) {
                $("#current_notes").html(data);
            });
    }

    
    $("#kpo_m_send").submit(function() {
        $.post("/default/kpo/sendkpo", { 
            email: $("#s_mail").val(),
            msg: $("#msg").val(),
            id: $("#s_id").val()
        },
        function(data) {
            $(".msg_field").html(data).fadeIn("slow");
            $("#kpo_m_send").slideUp("slow");

            $(".again").click( function () {
                $("#kpo_m_send").slideDown("slow");
                $('.msg_field').html("Podaj adres na jaki chcesz wysłać kartę:");
            })
        });
        return false;
    });

    //    $('.contex').live('click', function() {
    //        $(this).next('.contex_menu').toggle();
    //        $(this).children('span').removeClass("ui-icon-arrowthick-1-e");
    //        $(this).children('span').addClass("ui-icon-arrowthick-1-s");
    //        return false;
    //    });
    //    $('.contex_contain').bind('mouseleave', function() {
    //        $(this).children('ul:visible').hide();
    //        $(this).children('a').children('span').removeClass("ui-icon-arrowthick-1-s");
    //        $(this).children('a').children('span').addClass("ui-icon-arrowthick-1-e");
    //    });
    //    var list = $('.document_list tr td');
    

    $("#k_con .mark_star").live('click', function() {
        href= $(this).attr("href");
        link = $(this);
        $.get(href);
        link.toggleClass("on");
        return false;
    });
    $(".kpo_star .mark_star").live('click', function() {
        href= $(this).attr("href");
        value = $("#star_w").val();
        link = $(this);
        if(!value) {
            $("#star_w").val(1);
            link.addClass("on");
        }
        if(value==1) {
            $("#star_w").val(0);
            link.removeClass("on");
        } else {
            $("#star_w").val(1);
            link.addClass("on");
        }
        sendform();
        return false;
    });
    $(".filtr .mark_star").live('click', function() {
        href= $(this).attr("href");
        value = $("#star_w").val();
        link = $(this);
        if(!value) {
            $("#star_w").val(1);
            link.addClass("on");
        }
        if(value==1) {
            $("#star_w").val(0);
            link.removeClass("on");
        } else {
            $("#star_w").val(1);
            link.addClass("on");
        }
        //        sendform2();
        return false;
    });

    pokazano = 0;

    $('#numeracja_edit').click(function(){
        if(pokazano==0) {
            $("#validateTips").html("Ręczna zmiana numeru spowoduje przerwanie schematu numeracji!")
            $('.bledy_faktury_dialog').dialog('open');
        }
        pokazano = 1;
    })

    $('.nastepny_num').click(function() {
        typ = $(this).attr('href');
        $.getJSON('/nextnum', {
            typ: typ,
            nr: $("#nr").val()
        }, function(json) {
            $("#nr").val(json.nr);
            $("#numeracja_edit").text(json.format);
        })
        return false;
    })
    $('.poprzedni_num').click(function() {
        typ = $(this).attr('href');
        $.getJSON('/prevnum', {
            typ: typ,
            nr: $("#nr").val()
        }, function(json) {
            $("#nr").val(json.nr);
            $("#numeracja_edit").text(json.format);
        })
        return false;
    })
    $('.window_print').live('click', function() {
        href= $(this).attr('href');
        window.open(href,
            "name",
            "resizable=yes,scrollbars=yes,status=no,menubar=no,width=1100,height=500,location=no");
        return false;
    });

    $(".reset_list").click(function() {
        reset_list();
        //        sendform();
        return false;
    });
    $(".reset_list2").click(function() {
        reset_list2();
        //        sendform2();
        return false;
    });

    $(".star_marked").click(function() {
        $("#star_w").val('1');
        sendform();
        return false;
    });

    $(".star_nomarked").click(function() {
        $("#star_w").val('0');
        sendform();
        return false;
    });

    $('.form div:odd').addClass('f_odd');

    $(".tooltip").hover(function() {
        alt = $(this).children('a').attr('title')
        div = $('<div class="tip">'+alt+'</div>')
        $(this).append(div);
    }, function() {
        $(".tip").remove();
    })

    $(".envelope a").live('mouseover', function() {
        $(this).parent().children('span').show();
    })

    $(".envelope a").live('mouseout', function() {
        $(this).parent().children('span').hide();
    })

    $(".termin_domyslny").live('click', function(data){
        href = $(this).attr('href')
        link = $(this)
        $.post(href, {}, function(data) {
            $(".termin_domyslny").show();
            $("#lista_terminow_platnosci").children(".default").removeClass('default')
            link.parent().parent().addClass('default')
            link.hide();
        })
        return false
    })

    $(".short_name").live('mouseover', function() {
        $(this).next(".full_name").show();
    })
    $(".short_name").live('mouseout', function() {
        $(this).next(".full_name").hide();
    })

    $(".editable").hover(function(){ 
        $(this).addClass("hovere");
    }, function(){
        $(this).removeClass("hovere");
    })

    $(".dodaj_pole").click(function() {
        towar_l = $("#towary_body tr:last").attr('id').split("_");
        idik = parseInt(towar_l[1])
        idik+=1
        pole = $('<tr id="towar_'+idik+'"><td><a href="#" class="del_row"><img src="/_p/gfx/new/usun_towar.gif" alt="" /></a></td><td><input type="text" class="text towary_search" class="towar" name="towar['+idik+'][nazwa]" /></td><td><input type="text" class="text towary_pkwiu" class="towar" name="towar['+idik+'][pkwiu]" /></td><td><input type="text" class="text towary_jm" class="towar" name="towar['+idik+'][jm]" /></td><td><input type="text" class="text towary_ilosc" id="ilosc'+idik+'" name="towar['+idik+'][ilosc]" value="1" onchange="zmien_ilosc('+idik+')" /></td><td><input type="text" class="text towary_cena_netto" id="cena'+idik+'" name="towar['+idik+'][netto]" onchange="zmien_cene_netto('+idik+')" /></td><td class="netto_cena"><input type="text" class="text towary_wartosc_netto" id="netto'+idik+'" name="towar['+idik+'][wartosc]" onchange="zmien_wartosc_netto('+idik+')" /></td><td><input type="text" class="text towary_stawka_vat" id="podatek'+idik+'" name="towar['+idik+'][stawka]" onchange="zmien_podatek_vat('+idik+')" value="22" />%</td><td><input type="text" class="text towary_kwota_vat" id="vat'+idik+'" class="towar" name="towar['+idik+'][vat]" readonly="readonly" /></td><td class="hide"><input type="text" class="text towary_wartosc_brutto" id="brutto'+idik+'" name="towar['+idik+'][brutto]" onchange="zmien_wartosc_brutto('+idik+')" /></td></tr>');
        $('#towary_body').append(pole);
        search_towar();

        return false;
    })
    $(".dodaj_pole_korekta").click(function() {
        towar_l = $("#towary_body tr:last").attr('id').split("_");
        idik = parseInt(towar_l[1])
        idik+=1
        string = '<tr id="towar_'+idik+'"><td><a href="#" class="del_row"><img src="/_p/gfx/new/usun_towar.gif" alt="" /></a></td><td><input type="text" class="text towary_search" class="towar" name="towar['+idik+'][nazwa]" /></td>';
        string += '<td><input type="text" class="text towary_pkwiu" class="towar" name="towar['+idik+'][pkwiu]" /></td><td><input type="text" class="text towary_jm" class="towar" name="towar['+idik+'][jm]" /></td>';
        string += '<td><input type="text" class="text towary_ilosc" id="ilosc'+idik+'" name="towar['+idik+'][ilosc]" value="1" onchange="zmien_ilosc('+idik+')" /></td>';
        string += '<td class="netto_cena"><input type="text" class="text towary_cena_netto" id="cena'+idik+'" name="towar['+idik+'][netto]" onchange="zmien_cene_netto('+idik+')" /></td><td><input type="text" class="text towary_wartosc_netto" id="netto'+idik+'" name="towar['+idik+'][wartosc]" onchange="zmien_wartosc_netto('+idik+')" /></td>';
        string += '<td><input type="text" class="text towary_stawka_vat" id="podatek'+idik+'" name="towar['+idik+'][stawka]" onchange="zmien_podatek_vat('+idik+')" value="22" />%</td><td><input type="text" class="text towary_kwota_vat" id="vat'+idik+'" class="towar" name="towar['+idik+'][vat]" readonly="readonly" /></td>';
        string += '<td><input type="text" class="text towary_wartosc_brutto" id="brutto'+idik+'" name="towar['+idik+'][brutto]" onchange="zmien_wartosc_brutto('+idik+')" /></td></tr>';

        pole = $(string);
        $('#towary_body').append(pole);
        search_towar();

        return false;
    })
    $(".dodaj_pole_r").click(function() {
        towar_l = $("#towary_body tr:last").attr('id').split("_");
        idik = parseInt(towar_l[1])
        idik+=1
        pole = $('<tr id="towar_'+idik+'"><td><a href="#" class="del_row"><img src="/_p/gfx/new/usun_towar.gif" alt="" /></a></td><td><input type="text" class="text towary_search" class="towar" name="towar['+idik+'][nazwa]" /></td><td><input type="text" class="text towary_pkwiu" class="towar" name="towar['+idik+'][pkwiu]" /></td><td><input type="text" class="text towary_jm" class="towar" name="towar['+idik+'][jm]" /></td><td><input type="text" class="text towary_ilosc" id="ilosc'+idik+'" name="towar['+idik+'][ilosc]" value="1" onchange="zmien_ilosc('+idik+')" /></td><td class="netto_cena"><input type="text" class="text towary_cena_netto" id="cena'+idik+'" name="towar['+idik+'][netto]" onchange="zmien_cene_netto('+idik+')" /></td><td><input type="text" class="text towary_wartosc_netto" id="netto'+idik+'" name="towar['+idik+'][wartosc]" onchange="zmien_wartosc_netto('+idik+')" /></td></tr>');
        $('#towary_body').append(pole);
        search_towar();

        return false;
    })
    $('.del_row').live('click', function() {
        $(this).parent().parent().remove();
        licz_calosc();
        return false;
    })

    $("#zaplacono").change(function() {
        zaplacono();
    })

    $(".nieplac").live('click', function() {
        href_link = $(this).attr('href');
        but = $(this);
        $.getJSON(href_link+'/format/json', {}, function() {
            but.parent().html("<img src='/_p/gfx/new/zaplac.gif' alt='' />");
        })
        return false;
    });

    var kontrahent = $("#kontrahent")
    var firma_data = $("#firma_data")
    var numeracja_edit = $("#numeracja_edit")
    var razem_do_zaplaty = $("#razem_do_zaplaty")
    var towar = $("#tnazwa1")
    allFields = $([]).add(kontrahent).add(firma_data).add(numeracja_edit).add(razem_do_zaplaty).add(towar)
    $("#faktura_form").submit(function() {
        var bValid = true
        allFields.removeClass('ui-state-error')

        bValid = bValid && isKontrahent(kontrahent, "Kupujący", kontrahent.val())
        bValid = bValid && notEmpty(firma_data, "Sprzedający",firma_data.text())
        bValid = bValid && notEmpty(numeracja_edit, "Numer faktury",numeracja_edit.text())
        bValid = bValid && notEmpty(towar, "Nazwa towaru",towar.val())
        bValid = bValid && zaplata(razem_do_zaplaty, "Towar/usługa",razem_do_zaplaty.text())
        
        if(bValid) {
            $("#faktura_form input[name='numeracja']").val($("#numeracja_edit").text())
            $("#faktura_form input[name='sprzedajacy']").val($("#firma_data").html())
            $("#faktura_form input[name='kupujacy']").val($("#kontrahent_data").html())
            //            $("#faktura_form input[name='waluta']").val($("#waluta_faktury").text())
            //            $("#faktura_form input[name='rodzaj_platnosci']").val($("#rodzaj_platnosci strong").text())
            //            $("#faktura_form input[name='numer_konta']").val($("#numer_konta strong").text())
            $("#faktura_form input[name='razem_do_zaplaty']").val(parseFloat($("#razem_do_zaplaty").text()))
            $("#faktura_form input[name='pozostalo']").val(parseFloat($("#pozostalo_do_zaplaty").text()))
            $("#faktura_form input[name='uwagi']").val($("#uwagi_data").text())
            $("#faktura_form input[name='netto']").val(parseFloat($("#razem_netto").text()))
            $("#faktura_form input[name='brutto']").val(parseFloat($("#razem_brutto").text()))
            $("#faktura_form input[name='vat']").val(parseFloat($("#razem_vat").text()))
        } else {
            $(".bledy_faktury_dialog").dialog('open')
            return false
        }
    })
    $("#faktura_form2").submit(function() {
        var bValid = true
        allFields.removeClass('ui-state-error')

        bValid = bValid && notEmpty(firma_data, "Sprzedający",firma_data.text())
        bValid = bValid && notEmpty(towar, "Nazwa towaru",towar.val())
        bValid = bValid && zaplata(razem_do_zaplaty, "Towar/usługa",razem_do_zaplaty.text())

        if(bValid) {
            $("#faktura_form2 input[name='numeracja']").val($("#numeracja_edit").text())
            $("#faktura_form2 input[name='sprzedajacy']").val($("#firma_data").html())
            $("#faktura_form2 input[name='razem_do_zaplaty']").val(parseFloat($("#razem_do_zaplaty").text()))
            $("#faktura_form2 input[name='pozostalo']").val(parseFloat($("#pozostalo_do_zaplaty").text()))
            $("#faktura_form2 input[name='uwagi']").val($("#uwagi_data").text())
            $("#faktura_form2 input[name='netto']").val(parseFloat($("#razem_netto").text()))
            $("#faktura_form2 input[name='brutto']").val(parseFloat($("#razem_brutto").text()))
            $("#faktura_form2 input[name='vat']").val(parseFloat($("#razem_vat").text()))
        } else {
            $(".bledy_faktury_dialog").dialog('open')
            return false
        }
    })

    $('#f_opcje').change(function() {
        var val = ($(this).val())
        $.post('/settings/trescmaili', { 
            opcja: val
        }, function(data) {
            $("#f_msg").val(data)
        })
    })

    $(".usunieto_dialog").click(function() {
        $('.deleted_dialog').dialog('open');
    })

    $("#filtruje_faktury").click(function() {
        $("#k_con").hide();
        sendform2();
        return false;
    })

    $("#filtruje_kosztowe").click(function() {
        $("#k_con").hide();
        start  = $('#miesiac_start').val();
        stop  = $('#miesiac_stop').val();
        kontrahent  = $('#kontrahent_w').val();
        numer = $('#dok_w').val();
        tag = $('#tagi_w').val();
        status = $('#status_w').val();
        typ = $('#typ_w').val();
        
        if(kontrahent=='Kontrahent') {
            kontrahent = ''
        }
        if(numer=='Numer') {
            numer = ''
        }
        if(tag=='Tag') {
            tag = ''
        }
        
        $.post('/faktury/filtrkosztowe/format/html', {
            'miesiac_start': start ,
            'miesiac_stop': stop,
            'kontrahent':kontrahent, 
            'numer':numer,
            'typ_w':typ,
            'tag':tag,
            'status':status
        }, function(data) {
            $('#k_con').html(data);
            $("#k_con").show();
            makehover();
            koszttagform();
        })
        return false;
    })

    $("#resetuj_kosztowe").click(function() {
        $("#k_con").hide();
        start  = $('#miesiac_start').val();
        stop  = $('#miesiac_stop').val();
        kontrahent  = $('#kontrahent_w').val('Kontrahent');
        numer = $('#dok_w').val('Numer');
        tag = $('#tagi_w').val('Tag');
        status = $('#status_w').val('');
        typ = $('#typ_w').val();

        $.post('/faktury/filtrkosztowe/format/html',
            { 'miesiac_start': start , 'miesiac_stop': stop, 'kontrahent':'Kontrahent', 'numer':'Numer', 'typ_w': typ, 'tag':'Tag' },
            function(data) { $('#k_con').html(data); $("#k_con").show(); makehover();
        })
        return false;
    })

    $('.filtr_link_kpo').click(function() {
        $("#filtruje_kpo").trigger('submit');
        return false;
    })

    $("#filtruje_kpo").submit(function() {
        $("#k_con").hide();
        sendform();
        return false;
    })


    $(".ok").click(function() {
        $('#widgetCalendar').stop().animate({
            height: 0
        });
        miesiace = $("#widgetField span").text().split('/');
        sendform2();
        return false;
    })

    $(".ok_kosztowe").click(function() {
        $('#widgetCalendar').stop().animate({
            height: 0
        });
        miesiace = $("#widgetField span").text().split('/');
        start  = $('#miesiac_start').val();
        stop  = $('#miesiac_stop').val();
        $("#filtruje_kosztowe").trigger('click');
        return false;
    })

    $(".ok_uploader").click(function() {
        $('#widgetCalendar').stop().animate({
            height: 0
        });
        miesiace = $("#widgetField span").text().split('/');
        start  = $('#miesiac_start').val();
        stop  = $('#miesiac_stop').val();
        $.post('/upload/filtr/format/html', {
            'miesiac_start': start ,
            'miesiac_stop': stop
        }, function(data) {
            $('#k_con').html(data);
            makehover();
        })
        return false;
    })


    $(".ok_button_kpo").click(function() {
        $('#widgetCalendar').stop().animate({
            height: 0
        });
        miesiace = $("#widgetField span").text().split('/');
        sendform();
        return false;
    })

    $("#resetuj").click(function() {
        reset_list2();
        sendform2();
        return false;
    })
    $("#resetuj_kpo").click(function() {
        reset_list();
        sendform();
        return false;
    })

    $('.switcher li:first').fadeIn();
    $('.switcher .left').click(function() {
        visible = $('.switcher li:visible');
        if(visible.prev('li').html()) {
            visible.fadeOut("fast", function() {
                $(this).prev('li').fadeIn("fast")
            });
        }
        return false;

    })
    $('.switcher .right').click(function() {
        visible = $('.switcher li:visible');
        if(visible.next('li').html()) {
            visible.fadeOut("fast", function() {
                $(this).next('li').fadeIn("fast")
            });
        }
        return false;
    })

    $('.rejestracja_form').submit(function() {
        if(isNaN($("#regulamin:checked").val())) {
            $('.regulamin_dialog').dialog('open');
            return false;
        }
    })
    $('.pla a').show();
    size = $('#k_con tr').size();
    size = size-6;
    $(".fak #k_con tr:gt("+size+") td div").addClass('last_context');
    $(".kpo_list #k_con tr:gt("+size+") td div").addClass('last_context');

    $('.upload').click(function() {
        window.open( $(this).attr('href'), "mywindow","status=1,location=0,menubar=0,toolbar=0,width=800,height=600" );
        return false;
    })

    $('.suggester a').click(function() {
        $('.suggester form').slideToggle('slow');
        $(".suggester form #sugestia").focus();
    })
    $('.suggester form').submit(function() {
        var email = $(".suggester form #email").val();
        var msg = $(".suggester form #sugestia").val();
        var link = encodeURI(window.location);

        $.post('/suggester/send/format/html', { 
            'email':email,
            'msg':msg,
            'link': link
        }, function(data) {
            $('.suggester form').fadeOut()
            $('.suggester').html(data);
        });
        return false;
    })

    $('.logowanie').click(function() {
        $("#login_box").fadeIn();
        return false;
    })

    $('.close_box').click(function() {
        $(this).parent().fadeOut();
        return false;
    })

    $('.new_window').click(function() {
        var link = $(this).attr('href');
        window.open(link,"mywindow","status=1,scrollbars=1,toolbar=0,width=999,height=450");
        return false;
    //        window.open(link);
    })

    // TAGI

    //    $('.usertags a').click(function(){
    //        href = $(this).attr('href');
    //        $.post(href, {},
    //            function(data) {
    //                $('#k_con').html(data);
    //            });
    //            return false;
    //    })

    //    $('.filter_tag').focus(function(){
    //        if($(this).val()!=''){
    //            $('.filter_tag').removeAttr('value');
    //            id_f = $(this).parent().attr('id').substring(1);
    //            filtrujtagi(id_f);
    //        }
    //        return false;
    //    })
    //
    //    $('.filter_tag').keyup(function(){
    //        filter_val = $(this).val();
    //        $('.filter_tag').attr('value',filter_val);
    //        id_f = $(this).parent().attr('id').substring(1);
    //        filtrujtagi(id_f);
    //        return false;
    //    })


    $(".invoice_new_tag_name").autocomplete('/tagi/allinvoiceautocomplete', {
        width: 300,
        multiple: true,
        matchContains: true,
        formatItem: formatItemTag,
        formatResult: formatResult
    });
    
    $(".kpo_new_tag_name").autocomplete('/tagi/allkpoautocomplete', {
        width: 300,
        multiple: true,
        matchContains: true,
        formatItem: formatItemTag,
        formatResult: formatResult
    });

    $('.new_tag_button').live('click',function(){
        button = $(this);
        href = button.attr('href');
        nazwa_taga = $(this).parent().children('.new_tag_form').children('.invoice_new_tag_name').val();
        id_f = button.parent().attr('id').substring(1);
        if(nazwa_taga != ''){
            $.post(href, {
                nazwa: nazwa_taga
            },
            function(data) {
                $('.invoice_new_tag_name').removeAttr('value');
                odswierztagifaktury(id_f);
                odswierztagiuzytk();
            });
            return false;
        }
        else{
            return false;
        }
    })

    $('.kpo_new_tag_button').live('click',function(){
        button = $(this);
        href = button.attr('href');
        nazwa_taga = $(this).parent().children('.kpo_new_tag_form').children('.kpo_new_tag_name').val();
        kpo_id = button.parent().attr('id').substring(1);
        if(nazwa_taga != ''){
            $.post(href, {
                nazwa: nazwa_taga
            },
            function(data) {
                $('.kpo_new_tag_name').removeAttr('value');
                odswierztagikpo(kpo_id);
                odswierztagiuzytk();
            });
            return false;
        }
        else{
            return false;
        }
    })

    $('.new_tag_form').submit(function(){
        form = $(this);
        href = form.attr('action');
        nazwa_taga = form.children('.invoice_new_tag_name').val();
        id_f = form.parent().attr('id').substring(1);
        if(nazwa_taga != ''){
            $.post(href, {
                nazwa: nazwa_taga
            },
            function(data) {
                $('.invoice_new_tag_name').removeAttr('value');
                odswierztagifaktury(id_f);
                odswierztagiuzytk();
            });
            return false;
        }
        else{
            return false;
        }
    })


    koszttagform();
    $('.kpo_new_tag_form').submit(function(){
        form = $(this);
        href = $(this).attr('action');
        nazwa_taga = form.children('.kpo_new_tag_name').val();
        kpo_id = form.parent().attr('id').substring(2);
        if(nazwa_taga != ''){
            $.post(href, {
                nazwa: nazwa_taga
            },
            function(data) {
                $('.kpo_new_tag_name').removeAttr('value');
                odswierztagikpo(kpo_id);
                odswierztagiuzytk();
            });
            return false;
        }
        else{
            return false;
        }
    })


    //    $('.add_tag_button').live('click',function(){
    //        link = $(this);
    //        href = link.attr('href');
    //        $.post(href, {},
    //            function(data) {
    //                if(data=='error') {
    //                    alert('Faktura już ma taki tag.');
    //                }
    //                else{
    //                    id_f = link.parent().parent().parent().attr('id').substring(1);
    //                    $('#f'+id_f+' .tags_list').prepend(data);
    //                }
    //            });
    //        return false;
    //    })

    //    $('.usertags .del_tag_button').live('click',function(){
    //        link = $(this);
    //        if(confirm('Na pewno usunąć taga? Uważaj! Tag może być w wielu fakturach.')) {
    //            href = $(this).attr('href');
    //            $.post(href, {},
    //                function() {
    //                    //można by wyciąć id_f z hrefa?
    //                    id_f = link.parent().parent().parent().attr('id').substring(1);
    //                    //filtrujtagi(id_f);
    //                    odswierztagifaktury(id_f);
    //                });
    //        }
    //        return false;
    //    })

    $('.tags_list .del_tag_invoice_button').live('click',function(){
        link = $(this);
        href = $(this).attr('href');
        $.post(href, {},
            function(data) {
                if(data=='error') {
                    alert('Wystąpił błąd nie usunięto taga faktury.');
                }
                else{
                    id_f = link.parent().parent().parent().parent().attr('id').substring(1);
                    odswierztagifaktury(id_f);
                    odswierztagiuzytk();
                }
            });
        return false;
    })

    $('.del_tag_koszt_button').live('click',function(){
        link = $(this);
        href = $(this).attr('href');
        $.post(href, {},
            function(data) {
                if(data=='error') {
                    alert('Wystąpił błąd nie usunięto taga faktury.');
                }
                else{
                    link.parent().parent().fadeOut();
                }
            });
        return false;
    })

    $('.tags_list .del_tag_kpo_button').live('click',function(){
        link = $(this);
        href = $(this).attr('href');
        $.post(href, {},
            function(data) {
                if(data=='error') {
                    alert('Wystąpił błąd nie usunięto taga faktury.');
                }
                else{
                    kpo_id = link.parent().parent().parent().parent().attr('id').substring(1);
                    odswierztagikpo(kpo_id);
                    odswierztagiuzytk();
                }
            });
        return false;
    })

    //po otwarciu menu odświerza tagi
    //    $('.context_show').click(function(){
    //        id_f = $(this).parent().parent().attr('id');
    //        //filtrujtagi(id_f);
    //        /odswierztagifaktury(id_f);
    //    })
    //
    //    $('.context_menu').click(function(){
    //        kpo_id = $(this).parent().parent().attr('id');
    //        //filtrujtagi(id_f);
    //        odswierztagifaktury(kpo_id);
    //    })

    $('.up_tags_list a').click(function(){
        if(!$(this).parent().hasClass('active')){
            $(this).parent().addClass('active')
        }
        else{
            $(this).parent().removeClass('active')
        }
        $.post($(this).attr('href'));

        return false;
    });

    //tagi ustawienia
    $('.del_tag_set_button').live('click',function(){
        link = $(this);
        if(confirm('Na pewno usunąć taga? Uważaj! Tag może być w wielu fakturach.')) {
            href = $(this).attr('href');
            $.post(href, {},
                function() {
                    link.parent().remove();
                });
        }
        return false;
    })
    
    $('#new_tag_button').live('click',function(){
        button = $(this);
        href = $(this).attr('href');
        nazwa_taga = $('#new_tag_name').val();

        if(nazwa_taga != ''){
            $.post(href, {
                nazwa: nazwa_taga
            },
            function(data) {
                if(data=='exist') {
                    alert('Masz już taga o takiej nazwie. Nie dodano nowego.');
                }
                else{
                    odswierztagisettings();
                }
                $('#new_tag_name').removeAttr('value');
            });
            return false;
        }
        else{
            return false;
        }
    })

    // księgowość - kontakt

    $('.thread_form a').click(function(){
        href = $(this).attr('href');
        temat = $('#thread_topic').val();
        tresc = $('#post_content').val();
        if(temat != '' && tresc != ''){
            $.post(href, {
                temat: temat,
                tresc: tresc
            },
            function(data) {
                $('.brak_wynikow').remove();
                $('.thread_list tbody').prepend(data);
                $('#thread_topic').removeAttr('value');
                $('#post_content').val('');
            });
        }
        else{
            if(temat == '' && tresc == '') alert('Wpisz temat wątku oraz treść wiadomości.');
            else if(temat == '' && tresc != '') alert('Wpisz temat wątku.');
            else if(temat != '' && tresc == '') alert('Wpisz treść wiadomości.');
        }
        return false;
    })

    $('.post_form a').click(function(){
        href = $(this).attr('href');
        tresc = $('#post_content').val();
        if(tresc != ''){
            $.post(href, {
                tresc: tresc
            },
            function(data) {
                $('.brak_wynikow').remove();
                $('.post_list tbody').prepend(data);
                $('#post_content').val('');
            });
            return false;
        }
        else{
            alert('Wpisz tresc, aby dodać wiadomość.');
            return false;
        }
    })

    $('.del_thread, .del_post').live('click', function(){
        button = $(this);
        if(button.hasClass('del_thread')) text='<tr><td colspan="4">Brak wątków<td><tr>';
        if(button.hasClass('del_post')) text='<tr><td colspan="4">Brak wiadomości<td><tr>';

        href = $(this).attr('href');
        tbody = button.parent().parent().parent();
        if(confirm('Na pewno usunąć?')) {
            $.post(href, {},
                function(data) {
                    button.parent().parent().remove();
                    if(tbody.children().size()==0){
                        tbody.prepend(text)
                    }
                });
        }
        return false;
    })

    // księgowość - terminarz
    $('.termin_form a').click(function(){
        href = $(this).attr('href');
        nazwa = $('#termin_nazwa').val();
        data_terminu = $('#termin_data').val();
        if(nazwa != '' && data_terminu != ''){
            $.post(href, {
                nazwa: nazwa,
                data: data_terminu
            },
            function(data) {
                $('.brak_wynikow').remove();
                $('.termin_list tbody').prepend(data);
                $('#termin_nazwa').val('');
                $('#termin_data').val('');
            });
            return false;
        }
        else{
            if(nazwa == '' && data_terminu == '') alert('Wpisz nazwę oraz datę terminu.');
            else if(nazwa == '' && data_terminu != '') alert('Wpisz nazwę terminnu.');
            else if(nazwa != '' && data_terminu == '') alert('Wpisz datę terminu.');
            return false;
        }
    })

    $('.del_termin').live('click', function(){
        button = $(this);
        text='<tr><td colspan="4">Brak terminów<td><tr>';
        href = $(this).attr('href');
        tbody = button.parent().parent().parent();
        if(confirm('Na pewno usunąć termin?')) {
            $.post(href, {},
                function(data) {
                    button.parent().parent().remove();
                    if(tbody.children().size()==0){
                        tbody.prepend(text)
                    }
                });
        }
        return false;
    })

});

function odswierztagiuzytk(){
    $.post('/tagi/all/format/html', { },
        function(data) {
            $('.up_tags_list').html(data);
        });
}

function odswierztagifaktury(id_f){
    $.post('/tagi/invoicetags/id_f/'+id_f+'/format/html', { },
        function(data) {
            $('#f'+id_f+' .tags_list').html(data);
        });
}

function odswierztagikoszt(id_f){
    $.post('/tagi/koszttags/id_f/'+id_f+'/format/html', { },
        function(data) {
            $('#ko'+id_f+' .tags_list').html(data);
        });
}

function odswierztagikpo(kpo_id){
    $.post('/tagi/kpotags/kpo_id/'+kpo_id+'/format/html', { },
        function(data) {
            $('#k'+kpo_id+' .tags_list').html(data);
        });
}

function odswierztagisettings(){
    $.post('/default/tagi/index/format/html', {
        },
        function(data) {
            $('.tags_list').html(data);
        });
}

//function filtrujtagi(id_f, like){
//    if(like==null){
//        filter=$('.filter_tag').val();
//    }
//    else{
//        filter=like
//    }
//    $.post('/default/tagi/filterusertags', {
//        filter: filter,
//        id_f: id_f
//    },
//    function(data) {
//        $('#f'+id_f+' .usertags').html(data);
//    });
//}

function dodaj_towary() {
    var array = new Array()
    $("#towary_body tr").each(function(i) {
        var newArray = new Array();
        newArray.push($(this).children('td:eq(1)').children('input').val())
        newArray.push($(this).children('td:eq(2)').children('input').val())
        newArray.push($(this).children('td:eq(3)').children('input').val())
        newArray.push($(this).children('td:eq(4)').children('input').val())
        newArray.push($(this).children('td:eq(5)').children('input').val())
        newArray.push($(this).children('td:eq(6)').children('input').val())
        newArray.push($(this).children('td:eq(7)').children('input').val())
        newArray.push($(this).children('td:eq(8)').children('input').val())
        newArray.push($(this).children('td:eq(9)').children('input').val())
        array.push(newArray)
    })
    return array;
}
function search_towar() {
    $(".towary_search").autocomplete("/towary/wszystkie", {
        width: 180,
        autoFill: false,
        cacheLength: 1,
        formatItem: function(row) {
            returner = row[0];
            return returner;
        },
        formatResult: formatResult
    }).result(function(event, data) {
        id = $(this).parent().parent().attr('id').split("_");
        id = parseInt(id[1])

        $("#tnazwa"+id).val(data[0])
        $("#pkwiu"+id).val(data[1])
        $("#ilosc"+id).val(data[2])
        $("#cena"+id).val(data[3])
        $("#netto"+id).val(data[4])
        $("#podatek"+id).val(data[5])
        $("#vat"+id).val(data[6])
        $("#brutto"+id).val(data[7])

        licz_calosc()
    });
}

function reset_list() {
    $("#kod_w").val("Kod odpadu");
    $("#tagi_w_kpo").val("Tag");
    $("#nazwa_prz_w").val("Odbierający");
    $("#nazwa_pro_w").val("Transportujący");
    $("#nr_w").val("Nr KPO");
    $("#miesiac_w").val("");
    $("#rok_w").val("");
    $("#nazwa_pos_w").val("Przekazujący");
    $("#masa_w").val("");
    $("#star_w").val(0);
}
function reset_list2() {
    $("#tagi_w").val("Tag");
    $("#kontrahent_w").val("Kontrahent");
    $("#dok_w").val("Numer");
    $("#netto_w").val("");
    $("#brutto_w").val("");
    $("#data_wystawienia").val("");
    $("#data_zaplaty").val("");
    //    $("#oplacony_w").val(0);
    //    $("#nieoplacony_w").val(0);
    //    $("#oplacony_but").addClass("opacity");
    //    $("#nieoplacony_but").addClass("opacity");
    //    $("#przeterminowany_but").addClass("opacity");
    //    $("#przeterminowany_w").val(0);
    $("#status_w").val("");
    $("#star_w").val(0);
}
function insert(data, pre) {
    $("#"+pre+"_data").html(data[0]+"\nUlica: "+data[3]+"\nKod: "+data[5]+"\nMiasto: "+data[4]+"\nNIP: "+data[1]+"\nREGON: "+data[2]+"\nTelefon: "+data[7]);
    $("#id_"+pre).val(data[6]);
}

function insertodpad(data) {
    $("#id_o").val(data[3]);
    $("#rodzaj").val(data[1]);
    $("#kod").val(data[0]);
}

function clearodpad() {
    $("#rodzaj").val("");
    $("#kod").val("");
    $("#id_o").val("");
}

function clearfields(pre) {
    if($("#id_"+pre).val()!='0') {
        $("#miasto_"+pre).html("");
        $("#kod_"+pre).html("");
        $("#ulica_"+pre).html("");
        $("#id_"+pre).val("");
        $("#tel_"+pre).html("");
        $("#nazwa_"+pre).val("");
        $("#nip_"+pre).html("");
        $("#regon_"+pre).html("");
    }
}

function formatItem(row) {
    returner = row[0] + ", NIP:" +  row[1];
    if(row[2]!='') {
        returner += ", REGON " + row[2]
    }
    return returner;
}

function formatItemTag(row) {
    return row[0];
}

function formatResult(row) {
    return row[0];
}

function formatItemOdpad(row) {
    returner = row[0] + " "  +  row[1];
    if(row[2]!=0) {
        returner += " (niebezpieczny)"
    }
    return returner;
}

function sendform() {
    $("#k_con").hide();
    tagi_w_kpo = $("#tagi_w_kpo").val();
    nr_w = $("#nr_w").val();
    star_w = $("#star_w").val();
    kod_w = $("#kod_w").val();
    nazwa_prz_w = $("#nazwa_prz_w").val();
    nazwa_pos_w = $("#nazwa_pos_w").val();
    nazwa_pro_w = $("#nazwa_pro_w").val();
    masa_w = $("#masa_w").val();
    data_kpo = $("#data_kpo").val();
    miesiac_stop = $("#miesiac_stop").val();
    miesiac_start = $("#miesiac_start").val();
    
    if(nr_w=='Nr KPO') {
        nr_w = ''
    }
    if(tagi_w_kpo=='Tag') {
        tagi_w_kpo = ''
    }
    if(kod_w=='Kod odpadu') {
        kod_w = ''
    }
    if(nazwa_prz_w=='Odbierający') {
        nazwa_prz_w = ''
    }
    if(nazwa_pos_w=='Przekazujący') {
        nazwa_pos_w = ''
    }
    if(nazwa_pro_w=='Transportujący') {
        nazwa_pro_w = ''
    }

    $.post("/kpos", {
        "tagi_w_kpo": tagi_w_kpo,
        "nr_w" : nr_w,
        "kod_w": kod_w,
        "nazwa_prz_w": nazwa_prz_w,
        "nazwa_pos_w": nazwa_pos_w,
        "nazwa_pro_w": nazwa_pro_w,
        //        "masa_w": masa_w,
        //        "data_kpo": data_kpo,
        //        "star_w": star_w,
        "miesiac_start": miesiac_start,
        "miesiac_stop": miesiac_stop
    },
    function(data){
        $("#k_con").html(data);
        $("#k_con").show();
        size = $('#k_con tr').size();
        size = size-6;
        $("#k_con tr:gt("+size+") td div").addClass('last_context');

        $('.contex_contain').bind('mouseleave', function() {
            $(this).children('ul:visible').hide();
            $(this).children('a').removeClass("c_on");
        });
        makehover();
    });
    sumakpo();
}

function sendform2() {
    var tagi_w = $("#tagi_w").val();
    var kontrahent_w = $("#kontrahent_w").val();
    var dok_w = $("#dok_w").val();
    var netto_w = $("#netto_w").val();
    var brutto_w = $("#brutto_w").val();
    var miesiac_stop = $("#miesiac_stop").val();
    var miesiac_start = $("#miesiac_start").val();
    var miesiac_s = $("#miesiac_s").val();
    var rok_s = $("#rok_s").val();
    var typ_w = $("#typ_w").val();
    var status_w = $("#status_w").val();
    //    oplacony_w = $("#oplacony_w").val();
    //    nieoplacony_w = $("#nieoplacony_w").val();
    //    przeterminowany_w = $("#przeterminowany_w").val();
    $('.pla a').hide();
    $("#loader").show();

    if(kontrahent_w=='Kontrahent') {
        kontrahent_w = ''
    }
    if(tagi_w=='Tag') {
        tagi_w = ''
    }
    if(dok_w=='Numer') {
        dok_w = ''
    }
    
    $.post("/fakturas", {
        "kontrahent_w" : kontrahent_w,
        "tagi_w": tagi_w,
        "dok_w": dok_w,
        //        "netto_w": netto_w,
        //        "brutto_w": brutto_w,
        //        "data_wystawienia": data_wystawienia,
        //        "data_zaplaty": data_zaplaty,
        "miesiac_start": miesiac_start,
        "miesiac_stop": miesiac_stop,
        //        "oplacony_w": oplacony_w,
        //        "nieoplacony_w": nieoplacony_w,
        //        "przeterminowany_w": przeterminowany_w,
        "status": status_w,
        "typ": typ_w
    },
    function(data){
        $("#k_con").show();
        sumafaktury();
        $("#k_con").html(data);
        $("#loader").hide();

        $('.contex_contain').bind('mouseleave', function() {
            $(this).children('ul:visible').hide();
            $(this).children('a').removeClass("c_on");
        });

        $('.pla a').fadeIn();
        size = $('#k_con tr').size();
        size = size-6;
        $("#k_con tr:gt("+size+") td div").addClass('last_context');

        makehover();
    });
    
}

function sumakpo() {
    setTimeout(function() { 
        $.post("/kpo/suma", {}, function(data){
            $("#suma_field").html(data);
        });
    }, 500);
}

function sumafaktury() {
    $.getJSON("/suma_faktur", {
        },
        function(json){
            $("#suma_netto").html(json.suma_netto);
            $("#suma_brutto").html(json.suma_brutto);
            $("#suma_vat").html(json.suma_vat);
        });
}

String.prototype.br2nl =
    function() {
        return this.replace(/<br\s*\/?>/mg,"\n");
        return this;
    };
    
Date.prototype.format=function(format){
    var returnStr='';
    var replace=Date.replaceChars;
    for(var i=0;i<format.length;i++){
        var curChar=format.charAt(i);
        if(replace[curChar]){
            returnStr+=replace[curChar].call(this);
        }else{
            returnStr+=curChar;
        }
    }
    return returnStr;
};

Date.replaceChars={
    shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
    longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],
    shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
    longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
    d:function(){
        return(this.getDate()<10?'0':'')+this.getDate();
    },
    D:function(){
        return Date.replaceChars.shortDays[this.getDay()];
    },
    j:function(){
        return this.getDate();
    },
    l:function(){
        return Date.replaceChars.longDays[this.getDay()];
    },
    N:function(){
        return this.getDay()+1;
    },
    S:function(){
        return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));
    },
    w:function(){
        return this.getDay();
    },
    z:function(){
        return"Not Yet Supported";
    },
    W:function(){
        return"Not Yet Supported";
    },
    F:function(){
        return Date.replaceChars.longMonths[this.getMonth()];
    },
    m:function(){
        return(this.getMonth()<11?'0':'')+(this.getMonth()+1);
    },
    M:function(){
        return Date.replaceChars.shortMonths[this.getMonth()];
    },
    n:function(){
        return this.getMonth()+1;
    },
    t:function(){
        return"Not Yet Supported";
    },
    L:function(){
        return"Not Yet Supported";
    },
    o:function(){
        return"Not Supported";
    },
    Y:function(){
        return this.getFullYear();
    },
    y:function(){
        return(''+this.getFullYear()).substr(2);
    },
    a:function(){
        return this.getHours()<12?'am':'pm';
    },
    A:function(){
        return this.getHours()<12?'AM':'PM';
    },
    B:function(){
        return"Not Yet Supported";
    },
    g:function(){
        return this.getHours()%12||12;
    },
    G:function(){
        return this.getHours();
    },
    h:function(){
        return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);
    },
    H:function(){
        return(this.getHours()<10?'0':'')+this.getHours();
    },
    i:function(){
        return(this.getMinutes()<10?'0':'')+this.getMinutes();
    },
    s:function(){
        return(this.getSeconds()<10?'0':'')+this.getSeconds();
    },
    e:function(){
        return"Not Yet Supported";
    },
    I:function(){
        return"Not Supported";
    },
    O:function(){
        return(this.getTimezoneOffset()<0?'-':'+')+(this.getTimezoneOffset()/60<10?'0':'')+(this.getTimezoneOffset()/60)+'00';
    },
    T:function(){
        return"Not Yet Supported";
    },
    Z:function(){
        return this.getTimezoneOffset()*60;
    },
    c:function(){
        return"Not Yet Supported";
    },
    r:function(){
        return this.toString();
    },
    U:function(){
        return this.getTime()/1000;
    }
};

jQuery(function($){
    $.datepicker.regional['pl'] = {
        clearText: 'Wyczyść',
        clearStatus: '',
        closeText: 'Zamknij',
        closeStatus: 'Zamknij bez zmien',
        prevText: '<Poprzedni',
        prevStatus: 'Pokaż poprzedni miesiąc',
        nextText: 'Następny>',
        nextStatus: 'Pokaż kolejny miesiąc',
        currentText: 'Dzisiaj',
        currentStatus: 'Pokaż obecny miesiąc',
        monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
        monthNamesShort: ['Sty','Lu','Mar','Kwi','Maj','Cze','Lip','Sier','Wrz','Paź','Lis','Gru'],
        monthStatus: 'Pokaż inny miesiąc',
        yearStatus: 'Pokaż inny rok',
        weekHeader: 'Dzień',
        weekStatus: '',
        dayNames: ['Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota','Niedziela'],
        dayNamesShort: ['Pon','Wt','Śr','Czw','Pią','Sob','Nie'],
        dayNamesMin: ['N','P','W','Śr','Cz','P','S'],
        dayStatus: 'Ustaw DD jako pierwszy dzień w tygodniu',
        dateStatus: 'Wybierz DD, MM d',
        dateFormat: 'yy-mm-dd',
        firstDay: 1,
        initStatus: 'Wybierz datę',
        isRTL: false
    };
    $.datepicker.setDefaults($.datepicker.regional['pl']);
});

function koszttagform() {
    $('.koszt_tag_form').submit(function(){
        form = $(this);
        href = form.attr('action');
        nazwa_taga = form.children('#tag_form').val();
        id_f = form.parent().attr('id').substring(2);
        if(nazwa_taga != ''){
            $.post(href, {
                nazwa: nazwa_taga
            },
            function(data) {
                $('#tag_form').removeAttr('value');
                odswierztagikoszt(id_f);
            });
            return false;
        }
        else {
            return false;
        }
    })
    }

