$(function() {
    History.options.disableSuid = true;
    var urlPrefix = (!Modernizr.history) ? '!' : '';
    var router = new Router["default"]();
    router.map(function(match) {
        match("/tournaments").to("index");
        match("/tournaments/end").to("end");
    });
    var $preloader = $('#content_preloader');
    var $sideBar = $('ul.custom_menu');

    function loadPage(params) {
        var $ul = $('ul.stock_list');
        $ul.html('');
        $preloader.show();
        return $.ajax({
            url: params.url,
            type: 'GET',
            data: {block_to_render : params.block}
        }).then(function(response) {
            var html = response[params.block];
            if (!$ul.length) {
                $preloader.after($('<ul>', {'class': 'stock_list'}));
                $ul = $('ul.stock_list');
            }
            $ul.closest('.content').html(html);
            $preloader.hide();
        });
    }

    var handlers = {
        index: {
            model: function (params) {
                $sideBar.find('li').removeClass('active').eq(0).addClass('active');
                return loadPage({
                    url: '/tournaments',
                    block: 'template-1'
                });
            }
        },
        end: {
            model: function (params) {
                $sideBar.find('li').removeClass('active').eq(1).addClass('active');
                return loadPage({
                    url: '/tournaments/end',
                    block: 'template-1'
                });
            }
        }
    };

    router.getHandler = function(name) {
        return handlers[name];
    };

    router.updateURL = function(url) {
        History.pushState(null, document.title, url);
    };

    History.Adapter.bind(window, 'statechange', function(){
        var url = History.getState().hash;
        if (url.indexOf('!') != -1) {
            url = url.replace(/\/*!/g, '');
        }
        router.handleURL(url);
    });

    $('div.tournament_index_wrapper').on('click', '.js-menu-click, .pagination_wrapper a', function () {
        var url = $(this).attr('href');
        if (!url) {
            return true;
        }
        router.updateURL(urlPrefix + url);
        return false;
    });

    if (History.getState().hash.indexOf('!') != -1) {
        History.Adapter.trigger(window, 'statechange');
    }
});