var Fractal = Fractal || {};

Fractal.config = {

};

Fractal.breakpoint = null;

Fractal.events = jQuery({});

Fractal.boot = function() {

    // window resize debouncer
    var timer;
    jQuery(window).on('resize', function() {
        clearTimeout(timer);
        timer = setTimeout(function(){
            Fractal.events.trigger('resized');
        }, 200);
    });

    Fractal.events.on('resized', function(){
        var size = window.getComputedStyle(document.querySelector('body'), ':after').getPropertyValue('content').replace(/\'/g, '');
        Fractal.breakpoint = size;
    });

    Fractal.bindHandlers();

    FastClick.attach(document.body);
    Fractal.events.trigger('resized');

    $('body').on('click', function(){
        Fractal.events.trigger('body-clicked');
    });

    $(document).pjax('a[data-pjax]', '#main-content', {
            fragment: '#main-content'
        }).on('pjax:beforeSend', function(e, xhr, options){
            Fractal.events.trigger('main-content-preload', options.url);
        }).on('pjax:end', function(){
            Fractal.bindHandlers('#main-content');
            Fractal.events.trigger('main-content-loaded');
        });

    $(document).keyup(function(e) {
        if (e.keyCode == 27) Fractal.events.trigger('esc-pressed');
    });
};

Fractal.bindHandlers = function(root){
    var root = root || window.document;
    // load component handlers
    jQuery(root).find('[data-behaviour]').each(function(){
        var self = $(this);
        var handler = self.attr('data-behaviour');
        if ( handler ) {
            var handlerClassPath = ('Fractal/' + handler).split('/');
            var handlerClass = window;
            for ( var i = 0; i < handlerClassPath.length; i++ ) {
                handlerClass = handlerClass[handlerClassPath[i].toTitleCase()] || {};
            }
            if ( typeof handlerClass === 'function' ) {
                var handlerClass = new handlerClass(self);
                handlerClass.init();
            }
        }
    });
};

String.prototype.toTitleCase = function() {
    str = this.replace('-',' ').replace('_',' ');
    str = str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1);});
    return str.replace(/\W/g,'');
};
