$(document).ready(function(){
               	

        $("#opisBTN").click(function(){
                $(".description").toggle();
        });

        var branzeProfilObj=null;    //zawiera branże i podbranże wybrane przez użytkownika w jego profilu
        var listaBranzy;        //zawiera listę branż
        var path;

     
        
        if($('#BR-container').length>0){
             $("#BR-container").html('Pobieranie danych o branżach');
             $('#BR-nav input').attr('disabled',true);
            //pobieram ajaxem dane o branżach
            $.ajax({
                    url : '/jquery/AJAX-branze-odczyt.php',
                    data : $('#frmSearch').serialize(), // MEtoda serialize automatycznie zmienia dane wypełnionego formularza do formatu JSON - #m-folder-form - id forma
                    type : 'POST',
                    dataType : 'json',
                    success : function(response) {
                            // Dla urozmaicenia:
                            if (response.result == 1) {

                                   //obiekt z branżami ustawionymi przez użytkownika
                                    branzeProfilObj=response.branzeProfil;
                                    //lista branży z bazy danych
                                    listaBranzy=response.listaBranzy;

                                    //dodaje przycisk dodawania podbranzy
                                    branzeForm.addAddBTN();

                                    $("#BR-container").html('');

                                    //tworzymy puste bloki
                                    branzeForm.makeBRBlocks();

                                    $('#BR-nav input').attr('disabled',false);


                                    $('#RaportSubmitBTN').click(function(){
                                        
                                        //werfykacja walidacji formularza
                                        if($("#frmRaportKonfig").valid()){
                                            $('#BR-nav input').attr('disabled',true);
                                            
                                            $(branzeProfilObj).each(function(index,val){
                                               
                                                //var i=Number(id.substring(6));
                                                var i=index+1;
                                                branzeForm.switchToInfo(i);
                                            });
                                            
                                            //usuwam bloki z niewybraną branżą
                                            $(".BRblock").each(function(index){
                                                var counter=branzeForm.getIFromID($(this).attr('id'));
                                                if($('#BR-list_'+counter).val()=="Wybierz branżę") {
                                                    branzeForm.removeBRblock(counter);
                                                }
                                            });
                                            var formId=$(this).attr('rel');
                                            if(formId=='') formId='#frmSearch';
                                            else formId=('#'+formId).toString();

                                            $.ajax({
                                                    url : '/jquery/AJAX-branze-zapis.php',
                                                    data : $(formId).serialize(), // MEtoda serialize automatycznie zmienia dane wypełnionego formularza do formatu JSON - #m-folder-form - id forma
                                                    type : 'POST',
                                                    dataType : 'json',
                                                    success : function(response) {
                                                            // Dla urozmaicenia:
                                                            if (response.result == 1) {
                                                                   //obiekt z branżami ustawionymi przez użytkownika
                                                                   //$('#submitresponse').html(response.html)
                                                                   $('#submitresponse').html(response.komunikatOK);
                                                                   $('#tryb').val('edycja')
                                                                   if(response.trybZapisu=="nowy") {
                                                                       //zatwierdzenie formularza
                                                                       //$("#frmRaportKonfig").submit();
                                                                   }


                                                            }
                                                            $('#BR-nav input').attr('disabled',false);
                                                    }
                                            });
                                            } 
                                    })

                            }
                    }
            });
        }

        $('#resetBTN').click(function(){
           location.href='branzeForm.php';
        });

        
        $('#submitBTN').click(function(){
            $('#BR-nav input').attr('disabled',true);
            $.each(branzeProfilObj,function(id,val){
                var i=Number(id.substring(6));
                branzeForm.switchToInfo(i);
            });
            //usuwam bloki z niewybraną branżą
            $(".BRblock").each(function(index){
                var counter=branzeForm.getIFromID($(this).attr('id'));
                if($('#BR-list_'+counter).val()=="Wybierz branżę") {
                    branzeForm.removeBRblock(counter);
                }
            });
            var formId=$(this).attr('rel');
            if(formId=='') formId='#frmSearch';
            else formId=('#'+formId).toString();

            $.ajax({
                    url : '/jquery/AJAX-branze-zapis.php',
                    data : $(formId).serialize(), // MEtoda serialize automatycznie zmienia dane wypełnionego formularza do formatu JSON - #m-folder-form - id forma
                    type : 'POST',
                    dataType : 'json',
                    success : function(response) {
                            // Dla urozmaicenia:
                            if (response.result == 1) {
                                   //obiekt z branżami ustawionymi przez użytkownika
                                   //$('#submitresponse').html(response.html)
                                   //$('#submitresponse').html(response.komunikatOK);
                                   if(response.trybZapisu=="nowy") {
                                       //zatwierdzenie formularza
                                       $("#frmDaneUzytkownika").submit();
                                   }


                            }
                            $('#BR-nav input').attr('disabled',false);
                    }
            });
        });

                
        AjaxSaver.init();


        var branzeForm = {
                    //counter zlicza numer bloku branzy
                    counter : 0,
                    maxNumBranzy : 3,
                    numBranzy : 0,
                    maxCheckedPodbranzy : 100,

                    //tworzy ustaloną liczbę bloków branż ale nie zapełnione podbranżami
                    makeBRBlocks : function(){
                            var j=1;
                            //$("#BR-container").html('');
                            //$("#BR-container").html('Maksymalna liczba branży: '+this.maxNumBranzy+'<br>Maksymalna liczba podbranży: '+this.maxCheckedPodbranzy);
                            if(branzeProfilObj!=null)
                            $.each(branzeProfilObj,function(id,val){
                                var i=Number(id.substring(6));
                                //i=j
                                branzeForm.makeBRblock(i);
                                branzeForm.reloadPodbranze(i,val.branzaId);
                                branzeForm.applySettings(i);
                                branzeForm.switchToInfo(i);
                                j++;
                            })
                            branzeForm.verifyAllBRLists();

                    },

                    //tworzy blok dla branży - oraz umieszcza w nim elementy formularza
                    //przy uruchomieniu - select ma wszystkie branże, ale zaznaczenie tylko zgodnie z profilem,
                    //a podbranze zaladowane wszystkie z tej branży, ale zaznaczone tylko te z profilu

                    makeBRblock : function(counter) {
                            this.counter=counter;
                            branzeForm.numBranzy++;


                            if(branzeForm.numBranzy>=branzeForm.maxNumBranzy)
                                 this.ADDBTN.hide();
                            //tworze div dla bloku
                            //this.BRDiv=$('<div id="BR-div_'+this.counter+'" class="BRdiv"></div>');
                            this.BRDiv=$('<fieldset id="BR-div_'+this.counter+'" class="BRblock"><legend>Branża</legend></fieldset>');
                            this.BRDiv.appendTo($("#BR-container"));

                            //wstawiam liste
                            this.BRList=$('<select id="BR-list_'+this.counter+'" name="branzeProfil[branza'+this.counter+'][branzaId]"  class="BRselectList" ></select>');
                            this.BRList.appendTo($('#BR-div_'+this.counter));


                            //div dla tekstu alternatywnego
                            this.BRListAlt=$('<div id="BR-listAlt_'+this.counter+'" class="BR-listAlt"></div>');
                            this.BRListAlt.appendTo($('#BR-div_'+this.counter));
                            //$('<div>Podbranże:</div>').appendTo($('#BR-div_'+this.counter));

                            this.Wybierz=$('<option class="brOptionFirst">Wybierz branżę</option>');
                            this.Wybierz.appendTo(this.BRList);
                            //przy zmianie na liście branż
                            this.BRList.change(function(){
                                    if(this.selectedIndex!=0){
                                            //usuwam pierwszy wiersz z "Wybierz branżę"
                                            $('#BR-list_'+counter+' .brOptionFirst').remove();
                                            var counter=branzeForm.getIFromID($(this).attr('id'));
                                            var BRid=$(this).val();
                                            branzeForm.reloadPodbranze(counter,BRid);
                                            branzeForm.selectAll(counter);
                                            branzeForm.switchToEdit(counter);
                                            branzeForm.verifyAllBRLists();
                                    }
                            });



                            //zapelniamy liste
                            $.each(listaBranzy, function(i, val) {
                                $('<option value="'+val.id+'">'+val.nazwa+'</option>').appendTo("#BR-list_"+branzeForm.counter);
                            });



                            //div dla checkboxów
                            this.BRpodbrUL=$('<ol id="BR-podbr-UL_'+this.counter+'" class="BRpodbrUL"></ol>');
                            this.BRpodbrUL.appendTo($('#BR-div_'+this.counter));

                            this.BRnav=$('<div class="BRblockNav"></div>');
                            this.BRnav.appendTo(this.BRDiv);
                             //przycisk ok
                            this.OKbtn=$('<input type=button id="OKbtn_'+this.counter+'" name="OKbtn_'+this.counter+'"  value="OK"/>');
                            this.OKbtn.appendTo(this.BRnav);
                            this.OKbtn.click(function(){
                                var counter=branzeForm.getIFromID($(this).attr('id'));

                                //jesli zaznaczono jakieś podbranże
                                if($('#BR-list_'+counter).val()!="Wybierz branżę") {
                                    //aktualizuję obiekt branży
                                    var brName=("branza"+counter).toString();
                                    //var branzaObj=branzeProfilObj.branzeProfil[brName];
                                    if(branzeProfilObj==null) {
                                        branzeProfilObj={};
                                    }
                                    branzeProfilObj[brName]={
                                        "branzaId" : $('#BR-list_'+counter).val(),
                                        "podbranzaId" : []
                                    }
                                   $('#BR-podbr-UL_'+counter+' input:checked').each(function(index){
                                        branzeProfilObj[brName].podbranzaId[index]=$(this).val();
                                   });
                                   branzeForm.switchToInfo(counter);
                                }

                            });


                             //przycisk Anuluj
                            this.CANCELbtn=$('<input type=button  id="CANCELbtn_'+this.counter+'" name="CANCELbtn_'+this.counter+'"  value="Anuluj"/>');
                            this.CANCELbtn.appendTo(this.BRnav);
                            this.CANCELbtn.click(function(){
                                //cofniecie ustawien
                                var counter=branzeForm.getIFromID($(this).attr('id'));
                                var branzaObj=branzeProfilObj[("branza"+counter).toString()];
                                //console.log(branzeProfilObj)
                                if(branzaObj!=undefined) {

                                    //branzeForm.makeBRblock(branzaProfilObj);
                                    branzeForm.reloadPodbranze(counter,branzaObj.branzaId);
                                    branzeForm.applySettings(counter);
                                    branzeForm.switchToInfo(counter)
                                } else {
                                    //usuwam blok
                                    var checkedCount=$('#BR-podbr-UL_'+counter+' input:checked').length;
                                    if(checkedCount==0)
                                        branzeForm.removeBRblock(counter);
                                }



                            });


                             //przycisk Edycji
                            this.EDITbtn=$('<input type=button id="EDITbtn_'+this.counter+'" name="EDITbtn_'+this.counter+'" value="Zmień"/>');
                            this.EDITbtn.appendTo(this.BRnav);
                            this.EDITbtn.hide();
                            this.EDITbtn.click(function(){
                                //cofniecie ustawien
                                var counter=branzeForm.getIFromID($(this).attr('id'));
                               branzeForm.switchToEdit(counter)
                            });

                            //przycisk usuwania

                            this.DELETEbtn=$('<input type=button id="DELETEbtn_'+this.counter+'" name="DELETEbtn_'+this.counter+'"  value="Usuń"/>');
                            this.DELETEbtn.appendTo(this.BRnav);
                            this.DELETEbtn.click(function(){
                                //cofniecie ustawien
                                var counter=branzeForm.getIFromID($(this).attr('id'));
                               branzeForm.removeBRblock(counter);
                            });



                            //branzeForm.selectAll(counter);
                            branzeForm.branzeLegendsRenumerate();

                    },

                    //aktualizacja wyświetlonych numerów bloków branży na poprawną 1,2,3
                    branzeLegendsRenumerate : function (){
                        var i=0;
                        $('.BRblock').each(function(index){
                            $(this).children('legend').html('Branza '+(index+1));
                        });
                    },
                    getIFromID : function (ID){
                        var spl=ID.split("_");
                        return spl[1];
                    },
                    verifyAllBRLists : function(){
                        //1 odznacza wszystkie

                        $('.BRselectList option').attr('disabled',false);
                        
                        $('.BRselectList option').css('color','');
                        //2 zaznacza wybrane
                        $('.BRselectList').each(function(index){
                            var BRid=$(this).val();
                            branzeForm.verifyBRList(BRid);
                        });
                    },
                    verifyBRList : function (BRid){
                        var i=0;
                        //przebiegam po każdej liście branż w każdym bloku
                        $('.BRselectList').each(function(index){
                            i++;
                            //odczytuje ID wybranej branży w danym bloku
                            var thisBRid=$(this).val();
                            //BLOKUJEMY OPCJE NA POZOSTAŁYCH LISTACH KTÓRE SĄ Równe id branży na tej liście
                            if(BRid!=thisBRid){
                                $(this).children('option').each(function(index2){
                                    if(BRid==$(this).val()) {
                                        $(this).attr('disabled',true);
                                        $(this).css('color','#eee');
                                    }
                                });
                            }


                            //console.log();
                        });
                    },
                    //wymienia aktualną listę podbranży we wskazanym bloku na listę podbranż odpowiadającą wskazanemu idBranży
                    reloadPodbranze : function (counter,BRid) {
                        //czyszczenie listy podbranż
                        $('#BR-podbr-UL_'+counter).html('');
                        $('#BR-list_'+counter).val(BRid);

                        //usunięcie wybranej branży z pozostałych list wyboru

                        //console.log('reloadPodbranze')
                        var locPodb= podbranze[BRid];


                        //dodajemy przycisk "Cała branża"
                        this.liAll=$('<li><input type="checkbox" id="BR-podbrAll_'+counter+'" name="branzeProfil[branza'+counter+'][podbranzaId][]" value="wszystkie"><label for="BR-podbrAll_'+counter+'">Cała branża</label></li>');
                        this.liAll.appendTo('#BR-podbr-UL_'+counter);
                        this.BTNAll=$('#BR-podbrAll_'+counter);

                        this.BTNAll.click(function(){
                           var counter=branzeForm.getIFromID($(this).attr('id'));
                           $('#BR-podbr-UL_'+counter+' input:checkbox').attr('checked',false);
                           //$('#BR-podbr-UL_'+counter+' label').addClass('dimmed');

                            branzeForm.selectAll(counter);

                        });

                        //utworzenie kolejnych checkboxów
                        for(var i in locPodb) {

                            var arrayValue=locPodb[i];
                            var split=arrayValue.split("|");

                            this.BRcheckbox=branzeForm.makeCheckbox(counter,split[1],split[0]);
                            this.BRcheckbox.appendTo('#BR-podbr-UL_'+counter);
                            $('#BR-podbr-UL_'+counter+' label').css("cursor","pointer");
                            $('#BR-div_'+counter+' li').css('list-style-type','none');

                            //eventy dla checkboxów
                            $('#BR-'+counter+'-podbr_'+split[1]).click(function(){
                                //jeśli w trybie info, to nie nie działa
                                if($('#BR-list_'+counter).css('display')=='none') return false;

                                //odznaczam
                                $('#BR-podbrAll_'+counter).attr('checked',false);
                                var checkedCount=$('#BR-podbr-UL_'+counter+' input:checked').length;

                                //blokada powyżej 3
                                if(checkedCount==branzeForm.maxCheckedPodbranzy+1) {
                                    return false;
                                }


                                //liczba podbranzy
                                var liczbaPodbranzy=podbranze[BRid].length;
                                if(liczbaPodbranzy==checkedCount) {
                                    $('#BR-podbr-UL_'+counter+' input:checkbox').attr('checked',false);
                                    branzeForm.selectAll(counter);
                                } else {
                                    $('#BR-podbr-UL_'+counter+' li').removeClass('dimmed');
                                }
                                //zaznaczenie wszystkich checkboxów
                                if(checkedCount==0) {
                                    branzeForm.selectAll(counter);
                                }

                                //wygaszenie nadmiarowych checkboxów
                                if(checkedCount==branzeForm.maxCheckedPodbranzy){
                                    $('#BR-podbr-UL_'+counter+' input:not(:checked)').parent('li').addClass('dimmed');
                                    $('#BR-podbrAll_'+counter).parent('li').removeClass('dimmed');
                                }
                            })
                        }


                    },
                    selectAll : function(counter){
                        $('#BR-podbrAll_'+counter).attr('checked',true)
                        $('#BR-podbr-UL_'+counter+' li').addClass('dimmed');
                        $('#BR-podbr-UL_'+counter+' li').first().removeClass('dimmed');
                    },
                    removeBRblock : function(counter) {

                        $('#BR-div_'+counter).html('');
                        $('#BR-div_'+counter).remove();
                        branzeForm.numBranzy--;
                        if(branzeForm.numBranzy<3)
                                 this.ADDBTN.show();

                        branzeForm.branzeLegendsRenumerate();
                    },
                     //tworzy checkbox pojedynczej podbranży
                    makeCheckbox : function (counter,id,label){
                        this._BRcheckbox=$('<li ><input type="checkbox" id="BR-'+counter+'-podbr_'+id+'" name="branzeProfil[branza'+counter+'][podbranzaId][]" value="'+id+'"><label for="BR-'+counter+'-podbr_'+id+'">'+label+'</label></li>');

                        return this._BRcheckbox;
                    },
                    applySettings : function(counter){

                        //wybieram konkretny obiekt branży
                        var branzaObj=branzeProfilObj[("branza"+counter).toString()];
                        //po wszystkich elementach podbranży dla branża Id sprawdzamy, czy mamy zaznaczyc
                        for(i in branzaObj.podbranzaId) {
                            $('input[name="branzeProfil[branza'+counter+'][podbranzaId][]"]').each(function(){
                                if($(this).val()==branzaObj.podbranzaId[i]) {
                                    $(this).attr('checked', true);
                                }
                            })
                        }

                    },


                    //akcje EVENTOWE
                    //przełącza blok branży na informacyjny
                    switchToInfo : function(BRdivId){
                       $('#BR-listAlt_'+BRdivId).show();
                       $('#BR-listAlt_'+BRdivId).html($('#BR-list_'+BRdivId+' :selected').html());

                       //ukrywamy elementy
                        $('#OKbtn_'+BRdivId).hide();
                        $('#CANCELbtn_'+BRdivId).hide();
                        $('#BR-list_'+BRdivId).hide();
                        $('#BR-div_'+BRdivId+' input:not(:checked)').parents('li').hide();
                        $('#BR-div_'+BRdivId+' input:checkbox').hide();
                        $('#BR-div_'+BRdivId+' li').css('list-style-type','disc');
                        //jesli zaznaczono Wszystkie - wówczas wszystkie są ukrywane
                        if($('#BR-podbrAll_'+BRdivId).attr('checked')==true) {
                            $('#BR-div_'+BRdivId+' input').parents('li').hide();
                            $('#BR-podbrAll_'+BRdivId).parents('li').show();
                        }
                        //odkrywamy elementy
                        $('#EDITbtn_'+BRdivId).show();
                         $('#BR-podbr-UL_'+BRdivId).css({
                            'height':"",
                            'background':"",
                            'border':"none"
                        });
                        $('#BR-podbr-UL_'+BRdivId+' li').css({
                             'margin-bottom':'2px'
                        });
                        $('#BR-podbr-UL_'+BRdivId+' label').css("cursor","");
                    },

                    //przełącza blok  branży na formularz
                    switchToEdit : function(BRdivId){
                        $('#BR-listAlt_'+BRdivId).hide();
                        $('#BR-list_'+BRdivId).show();
                        $('#OKbtn_'+BRdivId).show();
                        $('#CANCELbtn_'+BRdivId).show();
                        $('#BR-div_'+BRdivId+' li').show();
                        $('#BR-div_'+BRdivId+' li').css('list-style-type','none');
                        $('#BR-div_'+BRdivId+' input:checkbox').show();

                        $('#EDITbtn_'+BRdivId).hide();

                        $('#BR-podbr-UL_'+BRdivId).css({
                            'height':'100px',
                            'background':'#fff',
                            'border-width' : '2px',
                            'border-style' : 'solid',
                            'border-color' : 'grey #eee #eee grey'
                        });
                        $('#BR-podbr-UL_'+BRdivId+' li').css({
                             'margin-bottom':'0px'
                        });
                        $('#BR-podbr-UL_'+BRdivId+' label').css("cursor","pointer");

                        var checkedCount=$('#BR-podbr-UL_'+BRdivId+' input:checked').length;
                        if(checkedCount==branzeForm.maxCheckedPodbranzy){
                            $('#BR-podbr-UL_'+BRdivId+' input:not(:checked)').parent('li').addClass('dimmed');
                            $('#BR-podbrAll_'+BRdivId).parent('li').removeClass('dimmed');
                        }

                    },
                    addAddBTN : function(){
                        this.ADDBTN=$('<input type=button value="+ Dodaj Branżę" name="dodaj-branze"/>');
                        this.ADDBTN.appendTo($('#BR-nav1'));
                        this.ADDBTN.click( function(){
                            branzeForm.counter++;

                            branzeForm.makeBRblock(branzeForm.counter);
                            branzeForm.verifyAllBRLists();
                            //
                        })
                    }
                };

});
