(function()
{
    'use strict';

    var page = jQuery(document);

    var defaults = {
        preloader: false,
        removalDelay: 300,
    };

    var i18n = {
        close: {
            lv: 'Aizvērt (Esc)',
            en: 'Close (Esc)',
            ru: 'Закрыть (Esc)'
        },
        loading: {
            lv: 'Notiek ielāde...',
            en: 'Loading...',
            ru: 'Загрузка...'
        },
        imageError: {
            lv: 'Neizdevās ielādēt <a href="%url%">attēlu</a>.',
            en: '<a href="%url%">The image</a> could not be loaded.',
            ru: 'Не удалось загрузить <a href="%url%">изображение</a>.'
        },
		galleryPrevious: {
		    lv: 'Iepriekšējais (kreisais bulttaustiņš)',
		    en: 'Previous (Left arrow key)',
		    ru: 'Предыдущее (клавиша со стрелкой влево)'
		},
		galleryNext: {
		    lv: 'Nākamais (labais bulttaustiņš)',
		    en: 'Next (Right arrow key)',
		    ru: 'Следующее (клавиша со стрелкой вправо)'
		},
    };

    var locale = jQuery('html').attr('lang');

    jQuery.extend(true, jQuery.magnificPopup.defaults, {
        tClose: i18n.close[locale],
        tLoading: i18n.loading[locale],
        image: {
            tError: i18n.imageError[locale]
        },
        gallery: {
            tCounter: '',
    		tPrev: i18n.galleryPrevious[locale],
    		tNext: i18n.galleryNext[locale],
        }
    });

    var enhance = function(dialog)
    {
        if (!dialog.attr('role'))
        {
            dialog.attr('role', 'dialog');
        }

        if (dialog.is('.modal'))
        {
            dialog.attr('aria-modal', 'true');
        }

        var dialogTitle = dialog.find('h1').first();

        if (dialogTitle.length)
        {
            var dialogTitleId = 'dialog-title-' + Math.random().toString(16).slice(2);

            dialogTitle.attr('id', dialogTitleId);
            dialog.attr('aria-labelledby', dialogTitleId);
        }

        return dialog;
    };

    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);
        var triggers = block.find('.has-dialog');

        triggers.each(function(index)
        {
            jQuery(this).trigger('dialog:attach');
        });
    });

    page.on('dialog:attach', function(event)
    {
        var trigger = jQuery(event.target);

        var type = 'inline';
        var href = trigger.attr('href');

        if (isImage(href))
        {
            type = 'image';
        }

        var params = {
            type: type,
            source: href,
            class: trigger.data('dialogClass')
        };

        /* 
            TODO: 
            add aria-haspopup="dialog" to trigger
            https://weboverhauls.github.io/demos/modal/modal_demo2.html
        */

        trigger.on('click', function(event)
        {
            event.preventDefault();

            if (jQuery.magnificPopup.instance.isOpen)
            {
                event.stopPropagation();
            }

            trigger.trigger('dialog:open', params);
        });
    });

    page.on('dialog:open', function(event, params)
    {
        if ('source' in params)
        {
            var type   = params.type;
            var source = params.source;
            var isModal = ('modal' in params) ? params.modal : false;

            if (typeof type == 'undefined')
            {
                type = 'inline';
            }

            if (type == 'inline')
            {
                source = jQuery(source);

                if (!source.length)
                {
                    return;
                }

                if (isModal)
                {
                    source.addClass('modal');
                }

                source = enhance(source);
            }

            var options = jQuery.extend(true, {}, defaults);

            options.type = type;
            options.items = {
                src: source
            };
            options.modal = isModal;
            options.mainEl = jQuery(event.target);
            options.mainClass = params.class;
            options.closeOnContentClick = (type == 'image');

            options.callbacks = {
                beforeOpen: function() {
                    jQuery.magnificPopup.instance.close = function() {
                        var triggerId = page.data('triggerId');

                        page.data('triggerId', null);

                        if (triggerId)
                        {
                            page.find('#' + triggerId).trigger('click');
                        }
                        else
                        {
                            jQuery.magnificPopup.proto.close(this);
                        }
                    }
                }
            };

            jQuery.magnificPopup.open(options);
        }
    });

    page.on('dialog:close', function(event)
    {
        jQuery.magnificPopup.close();
    });

    // close dialog when decline button pressed
    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);
        var declineButton = block.find('.dialog .button.decline');

        declineButton.on('click', function(event)
        {
            event.preventDefault();

            page.trigger('dialog:close');
        });
    });

}());
