/**
 * Klasa obslugi wyszukiwarki raportow
 * @author Wojciech Kowalik
 */
var SearchReports = function(){

    /**
     * zmienne
     */
    var options;
    var voivodeID;
    var countyID;
    var errorMsg = 'Wyst\u0105pił błąd komunikacji';
    var noAttributesValues = 'Prosz\u0119 wprowadzi\u0107 przynajmniej jedno kryterium wyszukania';

    /**
     * Wypelnia wojewodztwa
     * @param selectedOption int
     * @return void
     */
    this.fillVoivodes = function(selectedOption){

        $.ajax({
            url:'/?action=raports&make=makeVoivodes',
            type:'GET',
            dataType: 'json',
            async: true,
            success:function(data){

                if(data.state){

                    var select = $('#raports-search-locations-voivodes');
                    var selectCounties = $('#raports-search-locations-counties');
                    var selectCommunities = $('#raports-search-locations-communities');

                    if(select.prop) options = select.prop('options');
                        else options = select.attr('options');

                    if(selectCounties.prop) optionsSelectCounties = selectCounties.prop('options');
                        else optionsSelectCounties = selectCounties.attr('options');

                    if(selectCommunities.prop) optionsSelectCommunities = selectCommunities.prop('options');
                        else optionsSelectCommunities = selectCommunities.attr('options');

                    $('option', select).remove();

                    // wartosci domyslne
                    options[options.length] = new Option('wybierz:', '');
                    optionsSelectCounties[optionsSelectCounties.length] = new Option('wybierz województwo:', '');
                    optionsSelectCommunities[optionsSelectCommunities.length] = new Option('wybierz powiat:', '');

                    $.each(data.content, function(val, text) {
                        options[options.length] = new Option(text, val);
                    });

                    if(selectedOption)
                        select.val(selectedOption);

                    $('#search-spinner').hide();

                }else{
                    alert(errorMsg);
                }

            },

            beforeSend: function(){
                SearchReports.searchSpinner();
            },

            error:function() {
                alert(errorMsg);
            }
        });

    };

    /**
     * Wypelnia powiaty
     * @param selectedOption int
     * @param voivodeID int
     * @return void
     */
    this.fillCounties = function(selectedOption, voivodeID){

        $.ajax({
            url:'/?action=raports&make=makeCounties',
            type:'GET',
            dataType: 'json',
            data: {
                voivodeID: voivodeID
            },
            async: true,
            success:function(data){

                if(data.state){

                    var select = $('#raports-search-locations-counties');

                    if(select.prop) options = select.prop('options');
                    else options = select.attr('options');

                    $('option', select).remove();

                    // wyczysc wpisy gmin
                    $('#raports-search-locations-communities').find('option').
                    remove().end().append(new Option('wybierz powiat:', ''));

                    // wartosc domyslna
                    options[options.length] = new Option('wybierz:', '');

                    $.each(data.content, function(val, text) {
                        options[options.length] = new Option(text, val);
                    });

                    if(selectedOption)
                        select.val(selectedOption);

                    $('#search-spinner').hide();

                    // aktywuj wypełniony element
                    select.attr('disabled', false);

                }else{
                    alert(errorMsg);
                }

            },

            beforeSend: function(){
                SearchReports.searchSpinner();
            },

            error:function() {
                alert(errorMsg);
            }
        });

    };

    /**
     * Wypelnia gminy
     * @param selectedOption int
     * @param voivodeID int
     * @param countyID int
     * @return void
     */
    this.fillCommunities = function(selectedOption, voivodeID, countyID){

        $.ajax({
            url:'/?action=raports&make=makeCommunities',
            type:'GET',
            dataType: 'json',
            data: {
                voivodeID: voivodeID,
                countyID: countyID
            },
            async: true,
            success:function(data){

                if(data.state){

                    var select = $('#raports-search-locations-communities');

                    if(select.prop) options = select.prop('options');
                    else options = select.attr('options');

                    $('option', select).remove();

                    // wartosc domyslna
                    options[options.length] = new Option('wybierz:', '');

                    $.each(data.content, function(val, text) {
                        options[options.length] = new Option(text, val);
                    });

                    if(selectedOption)
                        select.val(selectedOption);

                    $('#search-spinner').hide();

                    // aktywuj wypełniony element
                    select.attr('disabled', false);

                }else{
                    alert(errorMsg);
                }

            },

            beforeSend: function(){
                SearchReports.searchSpinner();
            },

            error:function() {
                alert(errorMsg);
            }
        });

    };

    /**
     * Wypelnia typy
     * @param selectedOption int
     * @return void
     */
    this.fillTypes = function(selectedOption){

        $.ajax({
            url:'/?action=raports&make=makeTypes',
            type:'GET',
            dataType: 'json',
            async: true,
            success:function(data){

                if(data.state){

                    var select = $('#raports-search-others-type-institution');

                    if(select.prop) options = select.prop('options');
                    else options = select.attr('options');

                    $('option', select).remove();

                    // wartosc domyslna
                    options[options.length] = new Option('wybierz:', '');

                    $.each(data.content, function(val, text) {
                        options[options.length] = new Option(text, val);
                    });

                    if(selectedOption)
                        select.val(selectedOption);

                    $('#search-spinner').hide();

                }else{
                    alert(errorMsg);
                }

            },

            beforeSend: function(){
                SearchReports.searchSpinner();
            },

            error:function() {
                alert(errorMsg);
            }
        });

    };

    /**
     * Pokazuje spinner przy zapytaniach ajaxa
     * @return void
     */
    SearchReports.searchSpinner = function(){

        if($('#search-spinner').length){
            $('#search-spinner').show();
        }else{

            $('#raports-search').append("<div id='search-spinner' style='width: 100%; text-align:center; margin-top:50px;';>\n\
                                     <img src='/images/spinner.gif' alt=''>\n\
                                   </div>");
        }

    };

    /**
     * Czyści kryteria wyszukiwania
     * @return void
     */
    this.reload = function(){
        window.location.reload();
    }

    /**
     * Pobiera parametry do wyszukiwarki raportow
     * @return void
     */
    this.search = function(){

        var voivodes = $('#raports-search-locations-voivodes').val();
        var counties = $('#raports-search-locations-counties').val();
        var communities = $('#raports-search-locations-communities').val();
        var types = $('#raports-search-others-type-institution').val();
        var name = $('#raports-search-others-institution-name').val();

        // sprawdz czy wybrano kryteria
        if(voivodes == '' &&
            counties == '' &&
                communities == '' &&
                    types == '' &&
                        name == ''){

                        alert(noAttributesValues);
                        return;

                    }

        // kontener tabeli danych
        $("#data-tables-container").html('');

        // stworz tabele danych
        var table = $('<table>').attr('id', 'doc-table');
        var thead = $('<thead>');
        var tr = $('<tr>');

        tr.append($('<th>').addClass('date').text('Data'));
        tr.append($('<th>').addClass('type').text('Typ'));
        tr.append($('<th>').addClass('name').text('Nazwa szkoły/placówki'));
        tr.append($('<th>').addClass('see').text('Zobacz'));

        thead.append(tr);
        table.append(thead);

        // dolacz tabele do kontenera
        $("#data-tables-container").append(table);

        // inicjalizuj engine dataTable
        $("#doc-table").dataTable({

            sPaginationType : "full_numbers",
            oLanguage: {
            oPaginate: {
                    sFirst: " pierwsza ",
                    sLast : " ostatnia ",
                    sNext : " nast\u0119pna ",
                    sPrevious : " poprzednia "
            },

            sEmptyTable : "brak raportów",
            sInfoEmpty: "brak raportów",
            sZeroRecords : "brak raportów",
            sProcessing : "Trwa \u0142adowanie ...",
            sLengthMenu: "poka\u017c "+" _MENU_ "+" raportów na stronę",
            sInfo: "pokazuje " + " _START_ - _END_ "+ "z" +" _TOTAL_ "+" raportów",
            sInfoFiltered: "( _MAX_ "+ "wszystkich" +")",
            sSearch: "szukaj"
            },

            bFilter: false,
            bProcessing: true,
            bServerSide: true,
            bDestroy: true,
            sAjaxSource: "/?action=raports&make=search&vid="+voivodes+"&pid="+counties+"&cid="+communities+"&i_type="+types+"&i_name="+name,

            bAutoWidth: true,
            aaSorting: [[ 0, "desc" ]],

            aoColumns: [
            null,
            null,
            null,
            { bSortable: false }
            ]

        });

        $('#raports-search-container').removeClass('display-none');

    };

    /**
     * Obsługuje mapę województw
     * @return void
     */
    this.map = function(voivodeID){

      $('#raports-search-locations-voivodes').val(voivodeID);
      searchReports.fillCounties(0,voivodeID);
      searchReports.search();

    };


};
