/**
 * Created by macmini2 on 16/12/14.
 */
var advancedSearch = (function () {
    var elementAdvancedSearch = $('[data-advanced-search]');
    var bindFunction = function () {
        elementAdvancedSearch.on('change keyup', function (event) {
            if ((event.keyCode || event.which) == KEY_ESCAPE) {
                input.val(null);
            }
            if(event.hasOwnProperty('keyCode') || event.hasOwnProperty('which')) {
                var code = (typeof event.keyCode != 'undefined') ? event.keyCode : event.which;
                if(advancedSearch.exclude.indexOf(code) == -1) {
                    return;
                }
            }
            var target = event.target;
            event.preventDefault();

            if (event.type === "keyup" && typeof $(target).data('event-keyup') !== "undefined" || event.type === 'change') {
                submitForm($(this));
            }
        });

        var advancedSearchAction = function (url, formData) {
            var d = Q.defer();

            advancedSearch.call = $.get(url, formData)
                .success(function (data) {
                    d.resolve({data: data, formData: formData});
                })
                .fail(function (jqXHR) {
                    d.reject(new Error(jqXHR.responseText));
                });

            return d.promise;
        };

        var renderResults = function (data) {
            var d = Q.defer();

            window.history.replaceState({}, "", window.location.pathname+'?'+data.formData);

            var container = $('.pagination-container');

            var loading = container.find('.pagination-loader');
            if(loading.length) {
                loading.fadeOut(150);
            }

            container.fadeOut(200, function () {
                container.replaceWith(data.data).fadeIn(500);
                d.resolve(true);
                advancedSearch.onChange.dispatch(data.data);
            });

            return d.promise;
        };


        var submitForm = function (element) {
            if (typeof window.submitTimeout != 'undefined') {
                clearTimeout(window.submitTimeout);
            }

            var container = $('.pagination-container');

            if(!container.find('.pagination-loader').length) {
                container.append($('<div></div>', { 'class': 'pagination-loader' }));
            }


            window.submitTimeout = setTimeout(function () {
                var promise = Q.fcall(advancedSearchAction, $(element).prop('action'), $(element).serialize());

                if(advancedSearch.hasOwnProperty('call')) {
                    advancedSearch.call.abort();
                }

                promise
                    .then(renderResults)
                    .catch(function (error) {
                    })
                    .done();
            }, 250);
        };
    };

    var triggerAdvancedSearch = function () {
        $(elementAdvancedSearch).trigger('change');
    };

    return {
        init: function () {
            bindFunction();
        },
        trigger: function () {
            triggerAdvancedSearch();
        },
        exclude: (function() {
            var nletters = _.range(48, 91);
            var enter = [13, 8, KEY_ESCAPE];
            var npad = _.range(96, 112);
            var special = _.range(186, 223);

            return nletters
                .concat(enter)
                .concat(npad)
                .concat(special)
                ;
        })(),
        element: elementAdvancedSearch,
        onChange: new signals.Signal()
    }
})();

if ($(advancedSearch.element).length > 0) {
    advancedSearch.init();
};
