(function($){
    /**
     * Plugin jQuery zarządzający listami zależnymi
     * - format odpowiedzi powinien zawierać pola id i name
     *
     * @author Marek Kobyliński <marek.kobylinski@ffcreation.com>
     */
    $.fn.dataSelect = function(url)
    {
        /**
         * Obiekt główny
         */
        var _me = $(this);

        /**
         * URL do usługi ajax'owej
         */
        var _url = url;

        /**
         * Pole zależne
         */
        var _dependent = false;

        /**
         * _pola źródeł
         */
        var _sources = {};

        /**
         * funckcja callbackowa
         */
        var _callback = function(){};

        /**
         * stan kontrolki
         */
        var _state = '';

        /**
         * Callback ajax'owy odświeżający pole
         */
        function _refresh(response)
        {
            var _data = response.data;

            if(_data.length == 0){
                _me.find(':gt(0)').remove();
                return;
            }

            var _i = '';
            var _html = "";

            for(_i in _data){
                _html += '<option value="'+_data[_i].id+'" '+
                         (_data[_i].id == _state?'selected="selected"':'')+'>'+_data[_i].name+'</option>';
            }
            _me.find(':gt(0)').remove();
            _me.append(_html);
            _me.trigger("afterRefresh", [_this]);
        }

        /**
         * Zdarzenie zmiany wartości listy
         */
        _me.change(function(){
            _callback();
            _state = _me.val();
            if(_dependent){
                _dependent.refresh();
            }
        });

        /**
         * Publiczny interfejs obiektu
         */
        var _this = {
            /**
             * Ustawia podległy element
             */
            setDependent:function(object){
                _dependent = object;
                return _this;
            },
            /**
             * Ustawia źródło
             * - tablica identyfikatorów źródeł
             */
            setSource:function(sources){
                _sources = {};
                for(i in sources){
                    _sources[i] = $(sources[i]);
                }
                return _this;
            },
            /**
             * Metoda wywoływana przy zmianie wartości
             */
            setCallback:function(callback){
                _callback = callback;
                return _this;
            },
            /**
             * Odświerza element
             */
            refresh:function()
            {
                // Propagacja czyszczenia na pola podległe
                _me.change();

                // Jeśli brak jest źródeł przerywa prace
                if(_sources.length == 0){
                    // Czyszczenie formularza
                    _me.find(':gt(0)').remove();
                    return;
                }

                // Zebranie danych ze źródeł
                var _data = {};
                for(i in _sources){
                    _data[i] = _sources[i].val();
                }

                // Wysyłanie zapytania
                $.post(_url, _data, _refresh, "json");
                return _this;
            },

            /**
             * Dodaje zdarzenie umożliwiające podłączenie logiki
             * po dodświerzeniu
             */
            afterRefresh:function(v)
            {
                if(typeof v == 'function'){
                    _me.bind('afterRefresh', v);
                }else{
                    _me.unbind('afterRefresh');
                }
                return _this;
            },

            /**
             * Ustawia pozycję domyślną
             */
            setSelected:function(value)
            {
                _me.find('option[value='+value+']').attr('selected','selected');
            }
        }
        return _this;
    }
})(jQuery);