/* jquery.blockUI.js */
(function(A){
    A.blockUI=function(D,B,C){
        A.blockUI.impl.install(window,D,B,C)
    };

    A.blockUI.version=1.33;
    A.unblockUI=function(B){
        A.blockUI.impl.remove(window,B)
    };

    A.fn.block=function(D,B,C){
        return this.each(function(){
            if(!this.$pos_checked){
                if(A.css(this,"position")=="static"){
                    this.style.position="relative"
                }
                if(A.browser.msie){
                    this.style.zoom=1
                }
                this.$pos_checked=1
            }
            A.blockUI.impl.install(this,D,B,C)
        })
    };

    A.fn.unblock=function(B){
        return this.each(function(){
            A.blockUI.impl.remove(this,B)
        })
    };

    A.fn.displayBox=function(K,L,I){
        var E=this[0];
        if(!E){
            return
        }
        var N=A(E);
        K=K||{};

        var M=N.width()||N.attr("width")||K.width||A.blockUI.defaults.displayBoxCSS.width;
        var J=N.height()||N.attr("height")||K.height||A.blockUI.defaults.displayBoxCSS.height;
        if(M[M.length-1]=="%"){
            var H=document.documentElement.clientWidth||document.body.clientWidth;
            M=parseInt(M)||100;
            M=(M*H)/100
        }
        if(J[J.length-1]=="%"){
            var F=document.documentElement.clientHeight||document.body.clientHeight;
            J=parseInt(J)||100;
            J=(J*F)/100
        }
        var G="-"+parseInt(M)/2+"px";
        var C="-"+parseInt(J)/2+"px";
        var D=navigator.userAgent.toLowerCase();
        var B={
            displayMode:L||1,
            noalpha:I&&/mac/.test(D)&&/firefox/.test(D)
        };

        A.blockUI.impl.install(window,E,{
            width:M,
            height:J,
            marginTop:C,
            marginLeft:G
        },B)
    };

    A.blockUI.defaults={
        pageMessage:"<h1>Please wait...</h1>",
        elementMessage:"",
        overlayCSS:{
            backgroundColor:"#fff",
            opacity:"0.5"
        },
        pageMessageCSS:{
            width:"250px",
            margin:"-50px 0 0 -125px",
            top:"50%",
            left:"50%",
            textAlign:"center",
            color:"#000",
            backgroundColor:"#fff",
            border:"3px solid #aaa"
        },
        elementMessageCSS:{
            width:"250px",
            padding:"10px",
            textAlign:"center",
            backgroundColor:"#fff"
        },
        displayBoxCSS:{
            width:"400px",
            height:"400px",
            top:"50%",
            left:"50%"
        },
        ie6Stretch:1,
        allowTabToLeave:0,
        closeMessage:"Click to close",
        fadeOut:1,
        fadeTime:400
    };

    A.blockUI.impl={
        box:null,
        boxCallback:null,
        pageBlock:null,
        pageBlockEls:[],
        op8:window.opera&&window.opera.version()<9,
        ie6:A.browser.msie&&/MSIE 6.0/.test(navigator.userAgent),
        install:function(D,E,H,B){
            B=B||{};

            this.boxCallback=typeof B.displayMode=="function"?B.displayMode:null;
            this.box=B.displayMode?E:null;
            var J=(D==window);
            var O=this.op8||A.browser.mozilla&&/Linux/.test(navigator.platform);
            if(typeof B.alphaOverride!="undefined"){
                O=B.alphaOverride==0?1:0
            }
            if(J&&this.pageBlock){
                this.remove(window,{
                    fadeOut:0
                })
            }
            if(E&&typeof E=="object"&&!E.jquery&&!E.nodeType){
                H=E;
                E=null
            }
            E=E?(E.nodeType?A(E):E):J?A.blockUI.defaults.pageMessage:A.blockUI.defaults.elementMessage;
            if(B.displayMode){
                var P=jQuery.extend({},A.blockUI.defaults.displayBoxCSS)
            }else{
                var P=jQuery.extend({},J?A.blockUI.defaults.pageMessageCSS:A.blockUI.defaults.elementMessageCSS)
            }
            H=jQuery.extend(P,H||{});
            var I=(A.browser.msie)?A('<iframe class="blockUI" style="z-index:1000;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="javascript:false;"></iframe>'):A('<div class="blockUI" style="display:none"></div>');
            var M=A('<div class="blockUI" style="z-index:1001;cursor:wait;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');
            var F=J?A('<div class="blockUI blockMsg" style="z-index:1002;cursor:wait;padding:0;position:fixed"></div>'):A('<div class="blockUI" style="display:none;z-index:1002;cursor:wait;position:absolute"></div>');
            M.css("position",J?"fixed":"absolute");
            if(E){
                F.css(H)
            }
            if(!O){
                M.css(A.blockUI.defaults.overlayCSS)
            }
            if(this.op8){
                M.css({
                    width:""+D.clientWidth,
                    height:""+D.clientHeight
                })
            }
            if(A.browser.msie){
                I.css("opacity","0.0")
            }
            A([I[0],M[0],F[0]]).appendTo(J?"body":D);
            var L=A.browser.msie&&(!A.boxModel||A("object,embed",J?null:D).length>0);
            if(this.ie6||L){
                if(J&&A.blockUI.defaults.ie6Stretch&&A.boxModel){
                    A("html,body").css("height","100%")
                }
                if((this.ie6||!A.boxModel)&&!J){
                    var N=this.sz(D,"borderTopWidth"),G=this.sz(D,"borderLeftWidth");
                    var K=N?"(0 - "+N+")":0;
                    var C=G?"(0 - "+G+")":0
                }
                A.each([I,M,F],function(Q,S){
                    var R=S[0].style;
                    R.position="absolute";
                    if(Q<2){
                        J?R.setExpression("height",'document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + "px"'):R.setExpression("height",'this.parentNode.offsetHeight + "px"');
                        J?R.setExpression("width",'jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'):R.setExpression("width",'this.parentNode.offsetWidth + "px"');
                        if(C){
                            R.setExpression("left",C)
                        }
                        if(K){
                            R.setExpression("top",K)
                        }
                    }else{
                        if(J){
                            R.setExpression("top",'(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"')
                        }
                        R.marginTop=0
                    }
                })
            }
            if(B.displayMode){
                M.css("cursor","default").attr("title",A.blockUI.defaults.closeMessage);
                F.css("cursor","default");
                A([I[0],M[0],F[0]]).removeClass("blockUI").addClass("displayBox");
                A().click(A.blockUI.impl.boxHandler).bind("keypress",A.blockUI.impl.boxHandler)
            }else{
                this.bind(1,D)
            }
            F.append(E).show();
            if(E.jquery){
                E.show()
            }
            if(B.displayMode){
                return
            }
            if(J){
                this.pageBlock=F[0];
                this.pageBlockEls=A(":input:enabled:visible",this.pageBlock);
                setTimeout(this.focus,20)
            }else{
                this.center(F[0])
            }
        },
        remove:function(D,E){
            var F=A.extend({},A.blockUI.defaults,E);
            this.bind(0,D);
            var C=D==window;
            var B=C?A("body").children().filter(".blockUI"):A(".blockUI",D);
            if(C){
                this.pageBlock=this.pageBlockEls=null
            }
            if(F.fadeOut){
                B.fadeOut(F.fadeTime,function(){
                    if(this.parentNode){
                        this.parentNode.removeChild(this)
                    }
                })
            }else{
                B.remove()
            }
        },
        boxRemove:function(B){
            A().unbind("click",A.blockUI.impl.boxHandler).unbind("keypress",A.blockUI.impl.boxHandler);
            if(this.boxCallback){
                this.boxCallback(this.box)
            }
            A("body .displayBox").hide().remove()
        },
        handler:function(E){
            if(E.keyCode&&E.keyCode==9){
                if(A.blockUI.impl.pageBlock&&!A.blockUI.defaults.allowTabToLeave){
                    var D=A.blockUI.impl.pageBlockEls;
                    var C=!E.shiftKey&&E.target==D[D.length-1];
                    var B=E.shiftKey&&E.target==D[0];
                    if(C||B){
                        setTimeout(function(){
                            A.blockUI.impl.focus(B)
                        },10);
                        return false
                    }
                }
            }
            if(A(E.target).parents("div.blockMsg").length>0){
                return true
            }
            return A(E.target).parents().children().filter("div.blockUI").length==0
        },
        boxHandler:function(B){
            if((B.keyCode&&B.keyCode==27)||(B.type=="click"&&A(B.target).parents("div.blockMsg").length==0)){
                A.blockUI.impl.boxRemove()
            }
            return true
        },
        bind:function(B,E){
            var D=E==window;
            if(!B&&(D&&!this.pageBlock||!D&&!E.$blocked)){
                return
            }
            if(!D){
                E.$blocked=B
            }
            var C=A(E).find("a,:input");
            A.each(["mousedown","mouseup","keydown","keypress","click"],function(F,G){
                C[B?"bind":"unbind"](G,A.blockUI.impl.handler)
            })
        },
        focus:function(B){
            if(!A.blockUI.impl.pageBlockEls){
                return
            }
            var C=A.blockUI.impl.pageBlockEls[B===true?A.blockUI.impl.pageBlockEls.length-1:0];
            if(C){
                C.focus()
            }
        },
        center:function(E){
            var F=E.parentNode,D=E.style;
            var B=((F.offsetWidth-E.offsetWidth)/2)-this.sz(F,"borderLeftWidth");
            var C=((F.offsetHeight-E.offsetHeight)/2)-this.sz(F,"borderTopWidth");
            D.left=B>0?(B+"px"):"0";
            D.top=C>0?(C+"px"):"0"
        },
        sz:function(B,C){
            return parseInt(A.css(B,C))||0
        }
    }
})(jQuery)
/* date.js */
Date.dayNames=["Niedziela","Poniedziałek","Wtorek","Środa","Czwartek","Piątek","Sobota"];
Date.abbrDayNames=["Ni","Po","Wt","Śr","Cz","Pt","So"];
Date.monthNames=["Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień"];
Date.abbrMonthNames=["Sty","Lut","Mar","Kwi","Maj","Cze","Lip","Sie","Wrz","Paź","Lis","Gru"];
Date.firstDayOfWeek=1;
Date.format="dd mmmm yyyy";
(function(){
    function B(C,D){
        if(!Date.prototype[C]){
            Date.prototype[C]=D
        }
    }
    B("isLeapYear",function(){
        var C=this.getFullYear();
        return(C%4==0&&C%100!=0)||C%400==0
    });
    B("isWeekend",function(){
        return this.getDay()==0||this.getDay()==6
    });
    B("isWeekDay",function(){
        return !this.isWeekend()
    });
    B("getDaysInMonth",function(){
        return[31,(this.isLeapYear()?29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()]
    });
    B("getDayName",function(C){
        return C?Date.abbrDayNames[this.getDay()]:Date.dayNames[this.getDay()]
    });
    B("getMonthName",function(C){
        return C?Date.abbrMonthNames[this.getMonth()]:Date.monthNames[this.getMonth()]
    });
    B("getDayOfYear",function(){
        var C=new Date("1/1/"+this.getFullYear());
        return Math.floor((this.getTime()-C.getTime())/86400000)
    });
    B("getWeekOfYear",function(){
        return Math.ceil(this.getDayOfYear()/7)
    });
    B("setDayOfYear",function(C){
        this.setMonth(0);
        this.setDate(C);
        return this
    });
    B("addYears",function(C){
        this.setFullYear(this.getFullYear()+C);
        return this
    });
    B("addMonths",function(D){
        var C=this.getDate();
        this.setMonth(this.getMonth()+D);
        if(C>this.getDate()){
            this.addDays(-this.getDate())
        }
        return this
    });
    B("addDays",function(C){
        this.setDate(this.getDate()+C);
        return this
    });
    B("addHours",function(C){
        this.setHours(this.getHours()+C);
        return this
    });
    B("addMinutes",function(C){
        this.setMinutes(this.getMinutes()+C);
        return this
    });
    B("addSeconds",function(C){
        this.setSeconds(this.getSeconds()+C);
        return this
    });
    B("zeroTime",function(){
        this.setMilliseconds(0);
        this.setSeconds(0);
        this.setMinutes(0);
        this.setHours(0);
        return this
    });
    B("asString",function(){
        var C=Date.format;
        return C.split("yyyy").join(this.getFullYear()).split("yy").join(this.getYear()).split("mmmm").join(this.getMonthName(false)).split("mmm").join(this.getMonthName(true)).split("mm").join(A(this.getMonth()+1)).split("dd").join(A(this.getDate()))
    });
    Date.fromString=function(E){
        var F=Date.format;
        var H=new Date("01/01/1977");
        var I=F.indexOf("yyyy");
        if(I>-1){
            H.setFullYear(Number(E.substr(I,4)))
        }
        else{
            H.setYear(Number(E.substr(F.indexOf("yy"),2)))
        }
        var C=F.indexOf("mmm");
        if(C>-1){
            var G=E.substr(C,3);
            for(var D=0;D<Date.abbrMonthNames.length;D++){
                if(Date.abbrMonthNames[D]==G){
                    break
                }
            }
            H.setMonth(D)
        }else{
            H.setMonth(Number(E.substr(F.indexOf("mm"),2))-1)
        }
        H.setDate(Number(E.substr(F.indexOf("dd"),2)));
        if(isNaN(H.getTime())){
            return false
        }
        return H
    };

    var A=function(C){
        var D="0"+C;
        return D.substring(D.length-2)
    }
})()
/* passwordmeter.js MOD http://www.geekwisdom.com/dyn/passwdmeter */
function testPassword(B){
    var D=0;
    var C="weak";
    var A="";
    if(B.length<5){
        D=(D+4);
        A=A+"3 points for length ("+B.length+")\n"
    }
    else{
        if(B.length>4&&B.length<8){
            D=(D+12);
            A=A+"6 points for length ("+B.length+")\n"
        }else{
            if(B.length>7&&B.length<16){
                D=(D+20);
                A=A+"12 points for length ("+B.length+")\n"
            }else{
                if(B.length>15){
                    D=(D+25);
                    A=A+"18 point for length ("+B.length+")\n"
                }
            }
        }
    }
    if(B.match(/[a-z]/)){
        D=(D+1);
        A=A+"1 point for at least one lower case char\n"
    }
    if(B.match(/[A-Z]/)){
        D=(D+5);
        A=A+"5 points for at least one upper case char\n"
    }
    if(B.match(/\d+/)){
        D=(D+5);
        A=A+"5 points for at least one number\n"
    }
    if(B.match(/(.*[0-9].*[0-9].*[0-9])/)){
        D=(D+5);
        A=A+"5 points for at least three numbers\n"
    }
    if(B.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)){
        D=(D+5);
        A=A+"5 points for at least one special char\n"
    }
    if(B.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)){
        D=(D+5);
        A=A+"5 points for at least two special chars\n"
    }
    if(B.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)){
        D=(D+2);
        A=A+"2 combo points for upper and lower letters\n"
    }
    if(B.match(/([a-zA-Z])/)&&B.match(/([0-9])/)){
        D=(D+2);
        A=A+"2 combo points for letters and numbers\n"
    }
    if(B.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)){
        D=(D+2);
        A=A+"2 combo points for letters, numbers and special chars\n"
    }
    return(D)
}

var validator = null;
var ajax_in_progress = false;
var validator_ajax_status = false;

$().ready(function (){
    if($.browser.mozilla) {
        $('.html').each(function () {
            $(this).html($(this).html().replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;nbsp;/g, '&nbsp;'));
        });
        $('.html img').each(function () {
            $(this).load(function(){
                if ($(this).width() > 650) $(this).width(650);
            });
            if ($(this).width() > 650) $(this).width(650);
        });
    }

    $('.html img').each(function () {
        $(this).load(function(){
            if ($(this).width() > 650) $(this).width(650);
        });
        if ($(this).width() > 650) $(this).width(650);
    });

    $('.content_post_out img').after('<br/>');

    $('#f_comment .no-enter').keydown(function(event) {
        if (event.keyCode==13) {
            event.stopPropagation();
            event.preventDefault();
            return false;
        }
    });

    $('#f_comment_block').keydown(function(event) {
        return false;
    });

    if (window.navigator.appName=="Microsoft Internet Explorer"){
        $('#error_div').bgiframe();
        $("#error_div").css("position","absolute");
        $(window).bind('scroll', function() {
            var zmienna = parseInt(document.body.scrollTop);
            if (zmienna) {
                $("#error_div").css("top",(100+zmienna)+"px");
            } else {
                $("#error_div").css("top","100px");
            }
        });


    } else {
        $("#error_div").css("position","fixed");
    }

    $('.fields input, .fields textarea').focus(function(){
        $(this).addClass('bg50');
        if ($(this).hasClass('template')) {
            $(this).removeClass('template');
            $(this).val('');
        }
    }).blur(function(){
        $(this).removeClass('bg50');
    });

    jQuery.validator.addMethod("login", function(value) {
        return /^([a-z|A-Z|0-9])*$/.test(value);

    }, "");

    jQuery.validator.addMethod("pricevalidation", function(value) {
        return /^\d+([.,]\d{2})?$/.test(value);

    },"")

    jQuery.validator.addMethod("template", function(value, element) {
        return !$(element).hasClass('template');
    }, "");


    jQuery.validator.addMethod("validatelongword", function(value, element, maxlength) {
        var text = value.split(" ");
        for (var k=0;k<=(text.length-1);k++) {
            if ((!text[k].match(/\[img=http:\/\/(.*?)\]/)) && (text[k].length>maxlength)) {
                return false;
            }
        }
        return true;
    }, "");

    jQuery.validator.addMethod("ajax", function(value, element, param) {
        if ( this.optional(element) )
            return true;

        var previous = this.previousValue(element);
        this.settings.messages[element.name].remote = typeof previous.message == "function" ? previous.message(value) : previous.message;
        //if ( previous.old !== value ) {
        // Ajax za każdym razem a nie tylko po zmianie tekstu
        if ( true ) {
            //if ( previous.old !== value ) {
            previous.old = value;
            var validator = this;
            this.startRequest(element);
            var data = {};
            if ('object' == typeof(param)) {
                for(i=0;i<param.length;i++) {
                    data[param[i].key] = param[i].value;
                }
                param = data['url'];
            }
            data[element.name] = value;
            $(element).addClass('loading');
            jQuery.ajax({
                url: param,
                type: "POST",
                mode: "abort",
                port: "validate" + element.name,
                dataType: "json",
                data: data,
                success: function(response) {
                    $(element).removeClass('loading');
                    if (!response || response!=true) {
                        var errors = {};
                        errors[element.name] =  response || validator.defaultMessage( element, "remote" );
                        validator.showErrors(errors);
                        previous.valid = false;
                    }
                    else {
                        var submitted = validator.formSubmitted;
                        validator.prepareElement(element);
                        validator.formSubmitted = submitted;
                        validator.successList.push(element);
                        validator.showErrors();
                        previous.valid = false;
                    }
                    //previous.valid = response;
                    window.alert('valid'+previous.valid);
                    validator.stopRequest(element, response);
                }
            });
            return "pending";
        }else if( this.pending[element.name] ) {
            return "pending";
        }
        return previous.valid;
    },"");
				
    setup_validators();

    if ((null != $('#signin input')) && ($.browser.msie)) {
        $('#signin input').keypress(function (e){
            if (13 == e.which) {
                submit_login(back_url);
            }
        });
    }
});

function setup_validators(){
    fta = $('#form_topic_add');
    fsa = $('#form_subject_add');
    fr = $('#form_rejestracja');
    fm = $('#form_send_emails');
    fg = $('#form_add_groups');
    fa = $('#form_add_question');
    fat = $('#form_add_question_token');
    fn = $('#form_news_add');
    fac = $('#form_add_news_comment');
    faa = $('#form_add_ask_answer');
    fsp = $('#form_send_pw');
    fcpfc = $('#form_change_passwd_from_code');
    fk = $('#form_questionnaire');
    fc = $('#form_add_cosmetics');

    if (fr.length > 0) {
        validator = $('form').validate({
            rules: {
                f_login: {
                    required: true,
                    rangelength: [3, 16],
                    login: true,
                    ajax: site_base+'ajax/check_login/'
                },
                f_pass: {
                    required: true,
                    minlength: 6
                },
                f_pass_repeat: {
                    required: true,
                    equalTo: '#f_pass'
                },
                f_email: {
                    required: true,
                    email: true,
                    ajax: site_base+'ajax/check_email/'
                },
                f_sex: {
                    required: true
                }
            },
            messages: {
                f_login: {
                    required: 'Podaj login',
                    minlength: 'Twój login jest za krótki',
                    rangelength: 'Podany login jest za krótki',
                    login: 'Możesz użyć tylko liter i cyfr',
                    remote: 'Podany login jest już zajęty'
                },
                f_pass: {
                    required: 'Podaj swoje hasło',
                    minlength: 'Hasło musi mieć min. 6 znaków'
                },
                f_pass_repeat: {
                    required: 'Powtórz swoje hasło',
                    equalTo: 'Wpisane hasła są różne'
                },
                f_email: {
                    required: 'Podaj adres email',
                    email: 'Wpisz prawidłowy adres',
                    remote: 'Podany email jest już użyty'
                },
                f_email: {
                    required: 'Proszę wybrać płeć'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    }

    if (fta.length > 0) {
        validator =  $('#form_topic_add').validate({
            onfocusout: true,
            rules: {
                f_content: {
                    required: true,
                    validatelongword: 150
                }
            },
            messages: {
                f_content: {
                    required: 'Podaj treść odpowiedzi',
                    validatelongword: 'Maksymalna długość jedengo wyrazu wynosi 150 znaków, roździel długie wyrazy za pomocą spacji'

                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fsa.length>0){
        validator =  $('#form_subject_add').validate({
            onfocusout: true,
            rules: {
                f_title: {
                    required: true,
                    validatelongword: 50
                },
                f_content: {
                    validatelongword: 150
                }
            },
            messages: {
                f_title: {
                    required: 'Podaj temat',
                    validatelongword: 'Maksymalna długość jedengo wyrazu wynosi 50 znaków, roździel długie wyrazy za pomocą spacji'
                },
                f_content: {
                    validatelongword: 'Maksymalna długość jedengo wyrazu wynosi 150 znaków, roździel długie wyrazy za pomocą spacji'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fm.length>0){
        validator =  $('#form_send_emails').validate({
            onfocusout: true,
            rules: {
                f_email: {
                    required: true,
                    email: true,
                    ajax: site_base+'ajax/check_sends_invite/'
                }
            },
            messages: {
                f_name_to: {
                    template: 'Podaj imię bądź pseudo znajomej',
                    required: 'Podaj imię bądź pseudo znajomej',
                    minlength: 'Login/pseudo jest za krótkie'
                },
                f_email: {
                    template: 'Podaj adres email',
                    required: 'Podaj adres email',
                    email: 'Wpisz prawidłowy adres',
                    remote: 'Podany email jest już używany przez użytkowniczkę tego portalu'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fg.length>0){
        validator =  $('#form_add_groups').validate({
            onfocusout: true,
            rules: {
                f_title: {
                    required: true,
                    minlength: 4,
                    validatelongword: 25
                },
                f_categories: "required",
                f_description: {
                    maxlength: 500,
                    validatelongword: 50
                }
            },
            messages: {
                f_title: {
                    required: 'Podaj nazwę grupy',
                    minlength: 'Podana nazwa jest za krótka (minimum 4 znaki)',
                    ajax: 'Podana nazwa grupy jest już zajęta',
                    validatelongword: 'Maksymalna długość jedengo wyrazu wynosi 25 znaków, roździel długie wyrazy za pomocą spacji'
                },
                f_categories: {
                    required: 'Wybierz kategorię swojej grupy'
                },
                f_description: {
                    maxlength: 'Wprowadzony opis jest zbyt długi, do opisu możesz użyć maksymalnie 500 znaków',
                    validatelongword: 'Maksymalna długość jedengo wyrazu wynosi 50 znaków, roździel długie wyrazy za pomocą spacji'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if(fc.length>0){
        validator = $("#form_add_cosmetics").validate({
            onfocusout: true,
            rules: {
                f_title: {
                    required: true,
                    minlength: 4,
                    maxlength: 100,
                    validatelongword: 25
                },
                f_categories: "required",
                f_brand: "required",
                f_price: "pricevalidation",
                f_description: {
                    required: true,
                    minlength: 25,
                    maxlength: 4000,
                    validatelongword: 50
                }

            },
            messages: {
                f_title: {
                    required: 'Podaj nazwę produktu',
                    minlength: 'Podana nazwa jest za krótka (minimum 4 znaki)',
                    maxlength: 'Wprowadzony tekst jest zbyt długi, do opisu możesz użyć maksymalnie 100 znaków',
                    ajax: 'Podana nazwa produktu jest już zajęta',
                    validatelongword: 'Maksymalna długość jedengo wyrazu wynosi 25 znaków, roździel długie wyrazy za pomocą spacji'
                },
                f_categories: {
                    required: 'Wybierz kategorię swojego produktu'
                },
                f_brand: {
                    required: 'Podaj nazwę firmy'
                },
                f_price: {
                    pricevalidation: 'Wprowadzona wartość jest nieprawidłowa'
                },
                f_description: {
                    required: 'Wypełnij opis produktu',
                    minlength: 'Opis jest zbyt krótki (minimum 25 znaków)',
                    maxlength: 'Wprowadzony opis jest zbyt długi, do opisu możesz użyć maksymalnie 4000 znaków',
                    validatelongword: 'Maksymalna długość jedengo wyrazu wynosi 50 znaków, roździel długie wyrazy za pomocą spacji'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });

    } else if (fa.length>0){
        validator =  $('#form_add_question').validate({
            onfocusout: true,
            rules: {
                f_title:  "required"
            },
            messages: {
                f_title: {
                    required: 'Podaj treść pytania'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fat.length>0){
        validator =  $('#form_add_question_token').validate({
            onfocusout: true,
            rules: {
                f_title:  "required",
                f_token:  {
                    required: true,
                    rangelength: [5, 5]
                }
            },
            messages: {
                f_title: {
                    required: 'Podaj treść pytania'
                },
                f_token: {
                    required: 'Wprowadź liczbę z obrazka'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fn.length>0){
        validator =  $('#form_news_add').validate({
            onfocusout: true,
            rules: {
                f_title: {
                    required: true
                },
                f_url: {
                    required: true,
                    url: true
                },
                f_content: {
                    required: true
                }
            },
            messages: {
                f_title: {
                    required: 'Podaj tytuł newsa'
                },
                f_url: {
                    required: 'Wprowadź adres url',
                    url: 'Niepoprawny adres url'
                },
                f_content: {
                    template: 'Wprowadź opis newsa',
                    required: 'Wprowadź opis newsa'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fac.length>0){
        validator =  $('#form_add_news_comment').validate({
            onfocusout: true,
            rules: {
                f_comment: {
                    required: true
                }
            },
            messages: {
                f_comment: {
                    required: 'Twój komentarz jest pusty'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    }
    else if (faa.length>0){
        validator =  $('#form_add_ask_answer').validate({
            onfocusout: true,
            rules: {
                answer_content: {
                    required: true
                }
            },
            messages: {
                answer_content: {
                    required: 'Podaj treść odpowiedzi'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fsp.length>0){
        validator =  $('#form_send_pw').validate({
            onfocusout: true,
            rules: {
                f_content: {
                    required: true
                }
            },
            messages: {
                f_content: {
                    required: 'Podaj treść wiadomości'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fcpfc.length>0) {
        validator =  $('#form_change_passwd_from_code').validate({
            onfocusout: true,
            rules: {
                f_new_passwd: {
                    required: true,
                    minlength: 6
                },
                f_new_passwd_repeat: {
                    required: true,
                    equalTo: '#f_new_passwd'
                }
            },
            messages: {
                f_new_passwd: {
                    required: 'Podaj nowe hasło',
                    minlength: 'Hasło musi mieć min. 6 znaków'
                },
                f_new_passwd_repeat: {
                    required: 'Powtórz nowe hasło',
                    equalTo: 'Wpisane hasła są różne'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    } else if (fk.length>0) {
        validator =  $('#form_questionnaire').validate({
            onfocusout: true,
            rules: {
                login: {
                    required: true,
                    minlength: 3,
                    ajax: [{
                        'key':'url',
                        'value':'/ajax/check_login_from_questionnaire/'
                    },{
                        'key':'id',
                        'value':$('#form_quesionnaire_id').val()
                    }]
                }
            },
            messages: {
                login: {
                    required: 'Podaj Login',
                    minlength: 'Login musi mieć minimum 3 znaków',
                    remote: 'Podany login jest już zajęty'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    }
}

function ajax_it(action, params, callback){
    if (ajax_in_progress) {
        return false;
    }
    ajax_in_progress = true;
    $.ajax({
        type: "POST",
        url: site_base+"ajax/"+action,
        data: params,
        dataType: 'json',
        success: function(response){
            if (response.result) {
                callback(response);
            } else {
                show_error('<strong>'+response.errors[0].info+'</strong>');
            }
            ajax_in_progress = false;
        }
    });
    return;
}

function show_error(msg) {
  
    $("#error_div").show().animate({
        top:'100px',
        height:'130px'
    }, 1000 );
    $('#error_div_span').html(msg);
}

function hide_error(err) {
    $("#error_div").stop();
    $("#error_div").hide();
    $("#error_div").css('top','0px');
    $("#error_div").css('height','0px');

}

function checkPass() {
    strength = testPassword($('#f_pass')[0].value);
    $('#pass_strength').removeClass();

    if(strength < 10)
    {
        strengthHTML = 'bardzo słabe';
        strengthClass = 'pass_very_weak';
    }
    else if (strength > 9 && strength < 20)
    {
        strengthHTML = 'słabe';
        strengthClass = 'pass_weak';
    }
    else if (strength > 19 && strength < 25)
    {
        strengthHTML = 'umiarkowane';
        strengthClass = 'pass_medium';
    }
    else if (strength > 24 && strength < 30)
    {
        strengthHTML = 'mocne';
        strengthClass = 'pass_strong';
    }
    else
    {
        strengthHTML = 'bardzo mocne';
        strengthClass = 'pass_very_strong';
    }

    $('#pass_strength').html(strengthHTML);
    $('#pass_strength').addClass(strengthClass);
}

function check_field(id) {
    id = id.toString();
    field_name = new Array();
    field_name = field_name.concat(id.split("_"));
    field_name.shift();
    name = field_name.join('_');

    if ('' == id) {
        return true;
    }

    if ('checkbox' == $('#f_'+name)[0].type){
        if ($('#f_'+name).attr('checked')) {
            $('#err_'+name).css('visibility', 'hidden');
            return true;
        } else {
            $('#err_'+name).css('visibility', 'visible');
            return false;
        }
    } else {
        first_name = name.split('_repeat');

        if (1 < first_name.length) {
            first_name = first_name[0];
            if (($('#f_'+name)[0].value != $('#f_'+first_name)[0].value) ||
                ('' == $('#f_'+first_name)[0].value)) {

                $('#f_'+name).addClass('b40');
                if ('' != $('#f_'+first_name)[0].value) {
                    $('#err_'+name).css('visibility', 'visible');
                } else {
                    check_field('f_'+first_name);
                }

            } else {
                if (($('#f_'+name)[0].value == $('#f_'+first_name)[0].value)) {
                    $('#err_'+name).css('visibility', 'hidden');
                    $('#f_'+name).removeClass('b40');
                }
            }
        } else {
            if ('' == $('#f_'+name)[0].value) {
                $('#err_'+name).css('dvisibility', 'visible');
                $('#f_'+name).addClass('b40');
                return false;
            } else {
                $('#err_'+name).css('visibility', 'hidden');
                $('#f_'+name).removeClass('b40');
                return true;
            }
        }
    }
}

function is_field_empty(field) {

    field = field.toString();
    if (null == $(field)) {
        return true;
    } else {
        if ('' == $(field)[0].value) {
            $(field).addClass('error');
            return true;
        } else {
            $(field).removeClass('error');
            return false;
        }
    }
}

function are_fields_empty(fields) {
    result = false;
    jQuery.each(fields, function() {
        if (is_field_empty(this)) {
            result = true;
        }
    });
    return result;
};

function submit_login(back_url)
{
    $('.fields input').each(function(el){
        check_field(this.id);
    });

    if (('' != $('#f_login')[0].value) &&
        ('' != $('#f_pass')[0].value)) {
        form_ok = true;
    } else {
        form_ok = false;
    }


    if (form_ok)
    {
        var params = Object();
        params.login = $('#f_login')[0].value;
        params.pass = $('#f_pass')[0].value;
        params.remember = (true == $('#f_remember').attr('checked')) ? true : false;

        ajax_it('logowanie', params, function(){
            html = '<div class="title">Proszę czekać</div>'+
            '<div class="inner">Trwa logowanie</div>';
            $.extend($.blockUI.defaults.overlayCSS, {
                backgroundColor: '#000'
            });
            $.blockUI(html, {
                width: '300px',
                border: '8px solid #B3C704',
                padding: '0px'
            });
            self.location.href = site_base +back_url;
        });
    }
}

function submit_register() {
    check_field('f_accept');
    form_ok = validator.form() && $('#f_accept').attr('checked');

    if (form_ok) {
        var params = Object();
        params.login = $('#f_login').val();
        params.pass = $('#f_pass').val();
        params.email = $('#f_email').val();
        params.sex = $("input[@name='f_sex']:checked").val();
        if ('' != invitation_email) {
            params.invitation_email = invitation_email;
        }

        ajax_it('rejestracja', params, function(){
            self.location.href = site_base +'rejestracja/gotowe';
        });
    }
}

function submit_chpasswd(profil) {
    form_ok = false;
    form_ok = validator.form();
    if (form_ok) {
        var params = Object();
        params.old_pass = $('#f_old_passwd').val();
        params.new_pass = $('#f_new_passwd').val();

        ajax_it('zmien_haslo', params, function(){
            $('#change_password').hide();
            $('#f_old_passwd').val('');
            $('#f_new_passwd').val('');
            $('#f_new_passwd_repeat').val('');
            $('#profil_komunikat').show();
            $('#profil_info_naglowek').html('Twoje hasło zostało zmienione.');
            $('#profil_info_tresc').html('Teraz możesz powrócić do swojego <a href="/profil/'+profil+'>profilu</a>.');
        });
    }
}

function submit_chpasswd_from_code(code) {
    form_ok = false;
    form_ok = validator.form();
    if (form_ok) {
        var params = Object();
        params.new_pass = $('#f_new_passwd').val();
        params.code = code;
        ajax_it('zmien_haslo_from_code', params, function(){
            $('#change_password_from_code').hide();
            $('#change_passwd_ok').show();
        });
    }
}

function submit_chdemail(profil) {
    form_ok = false;
    form_ok = validator.form();
    if (form_ok) {
        var params = Object();
        params.email = $('#f_email').val();

        ajax_it('zmien_mail', params, function(){
            $('#change_email').hide();
            $('#old_email').html($('#f_email').val());
            $('#f_email').val('');
            $('#profil_komunikat').show();
            $('#profil_info_tresc').html('Teraz możesz powrócić do swojego <a href="/profil/'+profil+'">profilu</a>.');
            $('#profil_info_naglowek').html('Twój email został zmieniony.');
        });
    }
}

function submit_password() {
    form_ok = true;
    if ($('#f_pass_repeat')[0].value != $('#f_pass')[0].value)
    {
        $('#f_pass').addClass('error');
        $('#f_pass_repeat').addClass('error');
        form_ok = false;
    }

    if (form_ok)
    {
        var params = Object();
        params.login = $('#f_login')[0].value;
        params.pass = $('#f_pass')[0].value;
        params.code = code;

        ajax_it('haslo', params, function(){
            window.location = site_base +'profil/'+params.login;
        });
    }
}

function submit_logout() {
    ajax_it('wylogowanie', null, function(){
        window.location.reload();
    });

}

function submit_news_vote(news_id,typ)
{
    var params = Object();
    params.news_id = news_id;
    news_el = ('' == typ) ? news_id : typ + '_' + news_id;

    $('#news_'+news_el).fadeOut("fast");
    ajax_it('news_votes', params, function(response){
        $('#news_'+news_el).text( response.data[0] );
        $('#news_'+news_el).fadeIn("fast");
        $('#news_'+news_el).css('text-decoration','none');
        $('#news_'+news_el).css('cursor','default');
        $('#news_'+news_el)[0].setAttribute('title','');
        $('#news_'+news_el)[0].setAttribute('onclick','');
    });

}

function submit_news() {
    form_ok = true;
    form_ok = validator.form();

    if (form_ok)
    {
        var params = Object();
        params.title = $('#f_title')[0].value;
        params.url = $('#f_url')[0].value;
        params.content = $('#f_content')[0].value;

        ajax_it('news_add', params, function(){
            window.location = site_base +'newsy/';
        });
    }
}

function submit_groups() {
    form_ok = true;
    form_ok = validator.form();

    if (form_ok)
    {
        $('button_submit_group').attr('disabled','true');
        var params = Object();
        params.title = $('#f_title').val();
        params.content = $('#f_description').val();
        params.categories = $('#f_categories').val();
        params.type = $('input[name=f_type]').val();

        ajax_it('groups_dodaj', params, function(response){
            window.location = site_base + "grupy/" + response.data[0] +"/";
        });
        $('button_submit_group').attr('disabled','false');
    }
}

function uploadComplete(param,tresc) {
    if (param=='OK') {
        show_error('<strong>'+tresc+'</strong>');
    } else {
        show_error('<strong style="color:red;">'+tresc+'</strong>');
    }
}
function submit_question() {

    form_ok = validator.form();
    if (form_ok) {
        var params = Object();
        params.title = $('#f_title').val();
        params.content = $('#f_content').val();
        params.login = $('#f_login').val();
        params.token = $('#f_token').val();
        params.hash = $('#f_hash').val();

        ajax_it('ask_add', params, function(response){
            window.location = site_base+'forum/'+response.data[0];
        });

    }
}

function submit_group_topic(grupa) {
    form_ok = true;
    if (null == validator) {
        setup_validators();
    }

    form_ok = validator.form();

    if (form_ok) {
        $('button_topic_add').attr('disabled','true');
        var params = Object();
        params['f[title]'] = $('#f_title').val();
        params['f[content]'] = $('#f_content').val();
        params['f[groups_id]'] = grupa;
        ajax_it('group_add_topic', params, function(response){
            if (response.data[1]!=1) {
                self.location.href ='/grupy/'+grupa+"/topic/"+response.data[0]+"/?strona="+response.data[1];
            } else {
                self.location.href ='/grupy/'+grupa+"/topic/"+response.data[0]+"/";
            }
        });
        $('button_topic_add').attr('disabled','false');
    }
}

function submit_group_post(grupa,topic,page) {

    $('button_topic_add').attr('disabled','true');
    var params = Object();
    params['f[content]'] = $('#f_content').val();
    params['f[groups_id]'] = grupa;
    params['f[topic_id]'] = topic;
    ajax_it('group_add_post', params, function(response){
        if (page>1) {
            self.location.href ='/grupy/'+grupa+"/topic/"+topic+"/?strona="+page;
        } else {
            self.location.href ='/grupy/'+grupa+"/topic/"+topic+"/";
        }
    });
    $('button_topic_add').attr('disabled','false');

}

function submit_answer() {
    form_ok = true;
    form_ok = validator.form();
    if (form_ok)
    {
        var params = Object();
        params.question_id = question_id;
        params.login = $('#f_login').val();
        params.content = $('#answer_content')[0].value;

        ajax_it('ask_answer', params, function(){
            window.location.reload();
        });
    }
}

function submit_pw() {
    form_ok = true;
    var err_msg = '';
    form_ok = validator.form();
    if (form_ok)
    {
        var params = Object();
        params.to = user_login;
        params.content = $('#f_content')[0].value;

        ajax_it('wyslij_pw', params, function(){
            window.location = site_base +'profil/'+user_login+"/send_pw";
        });

    } else {
        show_error(err_msg);
    }
}

function submit_comment(news_id,title,typ) {

    form_ok = validator.form()
    if (form_ok)
    {
        var params = Object();
        params.comment = $('#f_comment').val();
        params.id = news_id;
        params.typ = typ;
        params.login = $('#f_login').val();

        ajax_it('news_add_comment', params, function(){
            window.location.reload();
        });
    }
}

function submit_contact() {
    form_ok = true;

    if (form_ok)
    {
        var params = Object();
        if (0 != $('#f_email').length) {
            params.email = $('#f_email').val();
        } else {
            params.email = '';
        }
        params.content = $('#f_content').val();

        ajax_it('contact', params, function(){
            show_error('<strong>Wysłano wiadomość. Odpowiedź dostaniesz na swój e-mail.</strong>');
        });
    }
}

function submit_send_email() {
    var params = new Object();

    form_ok = validator.form();

    if (form_ok){
        params.name_from = $('#f_name_from').val();
        params.email =  $('#f_email').val();

        $.ajax({
            type: "POST",
            url: site_base+"ajax/send_emails",
            data: params,
            dataType: 'json',
            success: function(response){
                if (response.result) {
                    $('#form_emails').hide();
                    $('#info_operation').show();
                } else {
                    show_error('<strong>'+response.errors[0].info+'</strong>');
                    $('#'+response.errors[1].info).addClass('form_mails_error');
                }
            }
        });

    }
}

function submit_recover() {
    form_ok = (('' != $('#f_login').val()) || ('' != $('#f_email').val()));

    if (form_ok)
    {
        $('#err_submit').css('visibility','hidden');
        var params = Object();
        params.login = $('#f_login').val();
        params.email = $('#f_email').val();


        ajax_it('pass_recover', params, function(){
            $('#f_login').val('');
            $('#f_email').val('');
            show_error('<strong>Sprawdź Swój e-mail aby odzyskać hasło.</strong>');
        });
    }
    else {
        $('#err_submit').css('visibility','visible');
    }
}

function show_add_topic_form () {
    $('#add_topic_form').fadeIn('slow');

}

function blink_on(obiekt) {
    $('#news_'+obiekt).addClass('b21');
}

function blink_off(obiekt) {
    $('#news_'+obiekt).addClass('b99');
}


function unhtmlize(tekst) {
    tekst=tekst.replace(/Ħ/g,"<");
    tekst=tekst.replace(/ħ/g,">");
    tekst=tekst.replace(/&amp;/g,"&");
    tekst=tekst.replace(/ĦĦ/g,"Ħ");
    tekst=tekst.replace(/ħħ/g,"ħ");
    return tekst
}

function html(obj_id,a) {
    var str='';
    ii=a.length;
    for (i = 0; i < ii ; i++) {
        str += unhtmlize(a[i]);
    }
    $('#'+obj_id)[0].innerHTML=str;
}

function show_form(pole){
    $('#profil_info_tresc').html('');
    $('#profil_info_naglowek').html('');
    if (pole==1) {
        $('#change_password').show();
        $('#change_email').hide();
        validator =  $('#form_change_passwd').validate({
            onfocusout: true,
            rules: {
                f_old_passwd: {
                    required: true,
                    ajax: site_base+'ajax/sprawdz_haslo/'
                },
                f_new_passwd: {
                    required: true,
                    minlength: 6
                },
                f_new_passwd_repeat: {
                    required: true,
                    equalTo: '#f_new_passwd'
                }
            },
            messages: {
                f_old_passwd: {
                    required: 'Podaj stare hasło',
                    minlength: 'Hasło musi mieć min. 6 znaków',
                    remote: 'To nie jest twoje stare hasło'
                },
                f_new_passwd: {
                    required: 'Podaj nowe hasło',
                    minlength: 'Hasło musi mieć min. 6 znaków'
                },
                f_new_passwd_repeat: {
                    required: 'Powtórz nowe hasło',
                    equalTo: 'Wpisane hasła są różne'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    }
    else if (pole==2) {
        $('#change_password').hide();
        $('#change_email').show();
        validator =  $('#form_change_email').validate({
            onfocusout: true,
            rules: {
                f_email: {
                    required: true,
                    email: true
                }
            },
            messages: {
                f_email: {
                    required: 'Podaj adres email',
                    email: 'Wpisz prawidłowy adres email'
                }
            },
            success: function(element){
                $(element).prev().addClass('valid');
            }
        });
    }
}

function show_add_question(){
    $('#button_add_ask_url').hide();
    $('#add_question').slideDown('fast');
}

function hide_add_question(){
    $('#button_add_ask_url').show();
    $('#add_question').slideUp('fast');
    $('form input, form textarea').val('');
}


function tab_on(tab_name) {
    if (tab_name=='tab_znajome') {
        $('#'+tab_name).removeClass("menu_big");
        $('#'+tab_name).addClass("menu_on_big");
    } else {
        $('#'+tab_name).removeClass("menu");
        $('#'+tab_name).addClass("menu_on");
    }
}


//function policz_znaki(maximum) {
//    var ile = maximum-$('#f_comment').val().length;
//    if(0>ile) {
//        $('#f_comment').val($('#f_comment').val().substring(0,maximum));
//        ile=maximum-$('#f_comment').val().length;
//        alert('Wprowadzony tekst jest za długi');
//    }
//    $('#f_comment_limit').html(ile);
//    return true;
//};

function policz_znaki_content(maximum) {
    var ile = maximum-$('#f_content').val().length;
    if (0>ile) {
        $('#f_content').val($('#f_content').val().substring(0,maximum));
        ile=maximum-$('#f_content').val().length;
        alert('Wprowadzony tekst jest za długi');
    }
    $('#f_comment_limit').html(ile);
    return true;
};

var editable_id =0;

function edit_ask(id) {
    editable_id = id;
    var params = Object();
    params.id = id;
    ajax_it('ask_answer_check_post', params, function(response){
        $('#content_post_'+id).append($('#edit_form'));
        $('#container_add_ask_answer').hide();
        $('#f_content_edit').val(response.data[0]);
        $('#edit_form').show();
        $('#content_'+id).hide();
        $('#button_div_button_edit_'+id).hide();
    });
}

function submit_edit_ask() {
    var params = Object();
    params.id = editable_id;
    params.content = $('#f_content_edit').val();
    ajax_it('ask_answer_rewrite_post', params, function(response){
        $('#content_'+editable_id).html(response.data[0]);
        $('#container_add_ask_answer').show();
        $('#edit_form').hide();
        $('#content_'+editable_id).show();
        $('#button_div_button_edit_'+editable_id).show();
    });
}

function submit_cancel_ask_post() {
    $('#container_add_ask_answer').show();
    $('#edit_form').hide();
    $('#content_'+editable_id).show();
    $('#button_div_button_edit_'+editable_id).show();
}

function edit_news(id) {
    editable_id = id;
    var params = Object();
    params.id = id;
    ajax_it('news_comment_check_post', params, function(response){
        $('#content_post_'+id).append($('#edit_form'));
        $('#comment_f').hide();
        $('#f_content_edit').val(response.data[0]);
        $('#edit_form').show();
        $('#content_'+id).hide();
        $('#button_div_button_edit_'+id).hide();
    });
}

function submit_edit_news() {
    var params = Object();
    params.id = editable_id;
    params.content = $('#f_content_edit').val();
    ajax_it('news_comment_rewrite_post', params, function(response){
        $('#content_'+editable_id).html(response.data[0]);
        $('#comment_f').show();
        $('#edit_form').hide();
        $('#content_'+editable_id).show();
        $('#button_div_button_edit_'+editable_id).show();
    });
}

function submit_cancel_news_post() {
    $('#comment_f').show();
    $('#edit_form').hide();
    $('#content_'+editable_id).show();
    $('#button_div_button_edit_'+editable_id).show();
}

function write_form_proust(questionaire_id) {
    var params = Object();
    $('.profil_form_description').each(function () {
        params['questionaire['+$(this).attr('id')+']'] = $(this).val();
    });
    params.login = $('#login').val();
    if (questionaire_id==0) {
        ajax_it('questionnaire_proust_add',params,function(response) {
            self.location.href = site_base+'kwestionariusz_prousta/'+response.data[0];

        });
    } else {
        params.id = questionaire_id;
        ajax_it('questionnaire_proust_write',params,function(response) {
            self.location.href = site_base+'kwestionariusz_prousta/'+response.data[0];
        });
    }
}

function del_news_comment(id,login) {
    if (confirm("Czy napewno chcesz usunąć komentarz napisany przez : '"+login+"' ?")) {
        var params = Object();
        params.id = id;
        ajax_it('news_comment_delete', params, function(response){
            $('#news_comment_'+id).slideUp('slow');
        });
    }
}

function del_ask_answer(id,login) {
    if (confirm("Czy napewno chcesz usunąć odpowiedź napisaną przez : '"+login+"' ?")) {
        var params = Object();
        params.id = id;
        ajax_it('ask_answer_delete', params, function(response){
            $('#ask_answer_'+id).slideUp('slow');
        });
    }
}

function delete_forum(id) {
    if (confirm("Czy napewno chcesz usunąć swój profil?Twoje dane zostana bezpowrotnie usunięte i nie będziesz już mieć mozliwości korzystania z serwisu.")) {
        var params = Object();
        params.id = id;
        ajax_it('ask_delete',params,function(response) {
            $('#content100').html('<h1>Te forum zostało pomyślnie usunięte!</h1>');
            setTimeout('location.href = '+site_base+'forum/',2000);
        });
    }
}


function var_dump(data,addwhitespace,safety,level) {
    var rtrn = '';
    var dt,it,spaces = '';
    if(!level) {
        level = 1;
    }
    for(var i=0; i<level; i++) {
        spaces += '   ';
    }//end for i<level
    if(typeof(data) != 'object') {
        dt = data;
        if(typeof(data) == 'string') {
            if(addwhitespace == 'html') {
                dt = dt.replace(/&/g,'&amp;');
                dt = dt.replace(/>/g,'&gt;');
                dt = dt.replace(/</g,'&lt;');
            }//end if addwhitespace == html
            dt = dt.replace(/\"/g,'\"');
            dt = '"' + dt + '"';
        }//end if typeof == string
        if(typeof(data) == 'function' && addwhitespace) {
            dt = new String(dt).replace(/\n/g,"\n"+spaces);
            if(addwhitespace == 'html') {
                dt = dt.replace(/&/g,'&amp;');
                dt = dt.replace(/>/g,'&gt;');
                dt = dt.replace(/</g,'&lt;');
            }//end if addwhitespace == html
        }//end if typeof == function
        if(typeof(data) == 'undefined') {
            dt = 'undefined';
        }//end if typeof == undefined
        if(addwhitespace == 'html') {
            if(typeof(dt) != 'string') {
                dt = new String(dt);
            }//end typeof != string
            dt = dt.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
        }//end if addwhitespace == html
        return dt;
    }//end if typeof != object && != array
    for (var x in data) {
        if(safety && (level > safety)) {
            dt = '*RECURSION*';
        } else {
            try {
                dt = var_dump(data[x],addwhitespace,safety,level+1);
            } catch (e) {
                continue;
            }
        }//end if-else level > safety
        it = var_dump(x,addwhitespace,safety,level+1);
        rtrn += it + ':' + dt + ',';
        if(addwhitespace) {
            rtrn += '\n'+spaces;
        }//end if addwhitespace
    }//end for...in
    if(addwhitespace) {
        rtrn = '{\n' + spaces + rtrn.substr(0,rtrn.length-(2+(level*3))) + '\n' + spaces.substr(0,spaces.length-3) + '}';
    } else {
        rtrn = '{' + rtrn.substr(0,rtrn.length-1) + '}';
    }//end if-else addwhitespace
    if(addwhitespace == 'html') {
        rtrn = rtrn.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
    }//end if addwhitespace == html
    return rtrn;
}

function zaladuj_grupy() {
    var params = Object();
    params.category = $("select[@name='category_id']").val();
    ajax_it('get_groups', params, function(response){
        $('#grupy_lim').empty();
        for (var w in response.data) {
            $('#grupy_lim').append('<option value="'+response.data[w]['id']+'">'+response.data[w]['title']+'</option>');
        }
    });
}

function cosmetics_categories(){
    var params = Object();
    params.category = $("select[@name='f_categories']").val();
    ajax_it('cosmetics_categories',params,function(response){
        $('#kat_lim').empty();
        for (var w in response.data) {
            $('#kat_lim').append('<option value="'+response.data[w]['id']+'">'+response.data[w]['title']+'</option>');
        }
    });
}

function submit_przenies(id,typ) {
    if (confirm("czy napewno prznieść wybrany temat do grupy \""+$("select[name=grupy_lim] option:selected").text()+"\"")) {
        var params = Object();
        params.groups_id = $("select[@name='grupy_lim']").val();
        params.id = id;
        if (params.groups=='' || params.id=='') {
            window.alert('nie wybrano ktegorii/grupy');
            return true;
        }
        if (typ==1) {
            ajax_it('move_to_group', params, function(response){
                self.location.href = "/grupy/"+response.data[1]+'/topic/'+response.data[0]+"/";
            });
        } else {
            ajax_it('move_to_group_news', params, function(response){
                self.location.href = "/grupy/"+response.data[1]+'/topic/'+response.data[0]+"/";
            });
        }
		
    }
}

function starsVoting(options) {
    var o = options;
    var value = 0;
    var div_container = $('#'+o.container);
    var div_stars = div_container.clone();
    var left = div_container.offset().left;
    div_stars.appendTo(div_container);
    div_stars.addClass(o.starsClass);
    div_stars.css({
        'width':o.startPercent+'%'
    });
    div_container.width(o.starsWidth*o.starsCount);
    div_container.mousemove(function (e) {
        value = Math.ceil((e.pageX-left)/o.starsWidth);
        div_stars.width(value * o.starsWidth);
    });
    div_stars.click(function () {
        o.starSelected(value);
    });
}


function cosmetic_vote(vote){

/**
    var params = new Object();
    params.vote = vote;
    params.cosmetic_id = cosmetic_id;

    ajax_it('cosmetics_vote',params,function(response){
        if(response.result){
            self.location.href ='/kosmetyk/'+cosmetic_id+'/'+cosmetic_title+"/";
        }else{
            show_error('<strong>'+response.errors[0].info+'</strong>');
        }
    })
     */

}

/**
$(document).ready(function(){

    var prev_id = null;
    var subcat = null;
    var time = 0;

    var submenu_id = readCookie('submenu_id');
    if(submenu_id != null){
        $($('#subcat_'+submenu_id)).show();
        prev_id = submenu_id;
    }

    $('.cosmetics_cat > a').click(function(){
        var id = $(this).attr('id').substr(4);
        subcat = '#subcat_'+id;

        if(id != prev_id && prev_id != null){
            if($(subcat+':visible').length < 1){
                $(subcat).show();
                createCookie('submenu_id',id,time);
            }else{
                $(subcat).hide();
                eraseCookie('submenu_id');
            }
            $('#subcat_'+prev_id).hide();

        }else if(id == prev_id){
            if($(subcat+':visible').length < 1){
                $(subcat).show();
                createCookie('submenu_id',id,time);
            }else{
                $(subcat).hide();
                eraseCookie('submenu_id');
            }   
        }
        else{
            $(subcat).show();
            createCookie('submenu_id',id,time);
        }
        prev_id = id;
        return false;
    });



});
*/


function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}


function policz_znaki(pole_obj, licznik_obj, limit) {
    var text = $('#'+pole_obj).val();
    var length = text.length;

    if(length >= limit){
        $('#'+pole_obj).val(text.substr(0,limit));
        $('#'+licznik_obj).html('Nie możesz wpisać więcej znaków!').css('color','red');

    }else{
        $('#'+licznik_obj).html(limit - length).css('color','black');

    }
}

//Zajefajna f-cja to powiększania elementu
function ResizeElement(event, element,max_line_length, line_height){
    var text_lines_count = 0;
    var text_lines = Array();
    var chars = 0;

    var val = element.val();
    var m = val.match(/\n/g);
    if (m){
        text_lines_count = m.length;
        text_lines = val.split(/\n/g);
    } else if(val!=''){
        text_lines_count = 0;
        text_lines.push(val);
    }

    for (var i in text_lines){
        if (text_lines[i].length > max_line_length){
            text_lines_count+=Math.round(text_lines[i].length/max_line_length);
        }
    }
    //alert(text_lines_count);
    var h = line_height + text_lines_count * 18;
    //e.animate({'height': h+ 'px'},100, function(){element.focus()});
    element.css({
        'height': h+ 'px'
    });
    element.focus();
}

function submit_file() {
    $('#f_upload').hide();
    $('#ajax_form').show();
    $('#f_upload').submit();
}



/**####################
 * KOSMETYKI
 *#####################
 */

function submit_cosmetic() {
    form_ok = true;
    form_ok = validator.form();

    if (form_ok)
    {
        var params = Object();
        params.title = $('#f_title').val();
        params.price = $('#f_price').val();
        params.description = $('#f_description').val();
        params.main_category = $('#f_categories').val();
        params.category = $('#kat_lim').val();
        params.brand = $('#f_brand').val();
        ajax_it('cosmetics_add',params,function(response){
            window.location = site_base + "kosmetyk/" + response.data[0] +"/";
        });
    }
}

function edit_cosmetic(cosmetic_id,action){
    
    if(action == 'open'){
        $('.edit_cosmetic').hide();
        $('.edit_cosmetic_h').show();
        $('#cosmetic_edit_options').hide();

    }else if(action == 'save'){
        
        form_ok = true;
        form_ok = validator.form();
        if(form_ok){
            var params = Object();
            params.cosmetic_id = cosmetic_id;
            params.description = $("#f_description").val();
            params.title = $("#f_title").val();
            params.brand = $("#f_brand").val();
            params.price = $("#f_price").val();

            ajax_it('cosmetics_edit',params,function(response){
                $('.edit_cosmetic_h').hide();
                $('.edit_cosmetic').show();
                $('#cosmetic_edit_options').show();

                $('#title').html(params.title);
                $('#price').html(params.price);
                $('#brand').html(params.brand);
            });

            if ($('#f_description').val()!='') {
                value = $('#f_description').val();
                value_change = value.replace(/\n/g, "<br/>");
                $('#description').html(value_change);
            } else {
                $('#description').html('');
            }
        }
    }else{
        $('.edit_cosmetic_h').hide();
        $('.edit_cosmetic').show();
        $('#cosmetic_edit_options').show();
    }
}

function delete_cosmetic(id,category){
    if (confirm("Czy napewno chcesz usunąć produkt?")){
        var params = Object();
        params.id = id;
        params.category = category;

        ajax_it('cosmetics_delete',params,function(response){
            if(response.result){
                self.location.href = '/kosmetyki/'+category+'/';
            }
        });
    }
}

function review_form_open(status){
    var form = '#review_form';
    if(status == true){
        $(form).show();
        $('#add_review_btn').hide();
        if($('#stars:has(div)').length<1){
            init_cosmetic_vote();
        }

    }else{
        $(form).hide();
        $('#add_review_btn').show();
    }
}

function init_cosmetic_vote(){
    var stars = new starsVoting({
        'container':'stars',
        'startPercent':0,
        'starsCount':5,
        'starsWidth':35,
        'starsClass':'stars_selected',
        starSelected:function(stars) {
            $('#user_vote').html(stars);
        }
    });
}

function submit_review(cosmetic_id) {

    var params = Object();
    params.content = $('#f_review').val();
    params.vote = $('#user_vote').html();
    params.cosmetic_id = cosmetic_id;

    ajax_it('cosmetics_review_add',params,function(response){
        self.location.href ='/kosmetyk/'+cosmetic_id+'/';
    });
}

function delete_cosmetic_review(cosmetic_id,user_id){
    var params = new Object();
    params.cosmetic_id = cosmetic_id;
    params.user_id = user_id

    ajax_it('cosmetics_review_delete',params,function(response){
        if(response.result){
            $('#review_'+user_id).hide('slow');
        }else{
            show_error('<strong>'+response.errors[0].info+'</strong>');
        }
    });
}

function edit_review(cosmetic_id, user_id, status){

    var review_desc = '#review_desc_'+user_id;
    var review_desc_h = '#review_desc_h_'+user_id;

    if(status == 'open'){
        $(review_desc).hide();
        $(review_desc_h).show();
    }else if(status == 'save'){
        var params = Object();
        params.cosmetic_id = cosmetic_id;
        params.user_id = user_id;
        params.description = $(review_desc_h+' > textarea').val();

        ajax_it('cosmetics_reviews_edit',params,function(response){
            $(review_desc).html(params.description);
            $(review_desc).show();
            $(review_desc_h).hide();

            if ($(review_desc_h+' > textarea').val()!='') {
                value = $(review_desc_h+' > textarea').val();
                value_change = value.replace(/\n/g, "<br/>");
                $(review_desc).html(value_change);
            } else {
                $(review_desc).html('');
            }
        });

    }
    else{
        $(review_desc).show();
        $(review_desc_h).hide();
    }
}

function policz_znaki_review(){
    policz_znaki('f_review', 'f_review_limit', 1000);
}

function policz_znaki_cosmetic(){
    policz_znaki('f_description', 'f_description_limit',4000);
}





function formTip(container,status,duration){
    
    var position = container.offset();
    var tooltip = $(container).children();

    if(status == true){

        tooltip.css({
            top: position.top-12,
            left: position.left+40
        }).show();

        var tippos = tooltip.offset();
        container.append('<div class="strz"></div>');
        $('.strz').css({
            top: tippos.top+10,
            left: tippos.left-14
        });
        
        
    }else{
        tooltip.hide();
        $('.strz').remove();
    }
}

function subcategory_on(id){
    $('#'+id).css('background','#e9f3ab');
}
