jQuery(function()
{
    'use strict';
    var page = jQuery(document);
    var body = page.find('body').first();

    page.on('layoutset', function()
    {
        // use innerWidth/innerHeight ratio instead of matchMedia for wider browser support
        var orientation = (window.innerWidth > window.innerHeight) ? 'landscape' : 'portrait';
        var current_orientation = page.data('orientation');

        var orientation_changed = (current_orientation != orientation);
        if (orientation_changed)
        {
            page.data('orientation', orientation);
        }


        var layout_value  = body.css('zIndex');
        var current_layout = page.data('layout');

        var layout = 'compact';
        if (layout_value == 6)
        {
            layout = 'medium';
        }
        else if (layout_value == 8)
        {
            layout = 'full';
        }

        var layout_changed = (current_layout != layout);
        if (layout_changed)
        {
            page.data('layout', layout);
        }


        // it is important that both events are only triggered AFTER both values have been set in page data
        // so that the new values are already available to handlers
        if (layout_changed)
        {
            page.trigger('layoutchange', layout);
        }

        if (orientation_changed)
        {
            // "orientationchange" gets triggered on document instead of window
            // therefore it does not clash with the native "orientationchange"
            page.trigger('orientationchange', orientation);
        }

    });

    page.on('layoutchange', function( _e, _layout)
    {
        // // uncomment this for debugging
        // var message = "layout changed to " + layout;
        // console.log( message );
    });

    page.on('orientationchange', function( e, _orientation )
    {
        // the native "orientationchange" event implemented by some browsers
        // gets triggered on the window element.

        // it is not used by this site
        // and this script triggers its own "orientationchange" events
        // on the document (page) instead of window

        // to prevent confusion the custom events are stopped at the document
        // so that they do not propogate up to window
        e.stopPropagation();

        // var message = "orientation changed to " + orientation;
        // console.log( message );
    });

    var resizer_timeout;

    jQuery(window).on('resize', function()
    {
        clearTimeout(resizer_timeout);
        resizer_timeout = setTimeout( function()
        {
            page.trigger('resizeend');
        }, 100);
    });

    page.on('resizeend', function()
    {
        page.trigger('layoutset');
    });

    // use setTimeout to trigger this after all scripts have been loaded
    // and attached their initial handlers for this event
    setTimeout( function()
    {
        page.trigger('resizeend');
    }, 0);


});

