/* Popup plugin
------------------------------------------------------------------------------------------------ */

(function($){
    $.fn.popup = function(settings) {

        if(!this.length)
            return;

        settings = $.extend({
            'margin'    : 20,   // Margin from the iframe popup
            'width'     : 700,  // Default popup width
            'height'    : 500  // Default popup height
        }, settings);

        // No inline popup on smartphones etc.

        if (/android|iphone|ipad|ipod|series60|symbian|windowsce|blackberry/i.test(navigator.userAgent))
            return;

        // Create iframe popup

        createIframePopup();

        // Open iframe popup

        $(this).click(function(){

            // Set hash

            var hash = location.hash;

            if (!hash) {
                location.hash = $(this).attr('id');
            }

            // Hide scrollbar and fadein overlay

            $('body, html').css('overflow', 'hidden');

            if (hash) {
                $(ip_overlay).css({
                    'opacity' : 0.8
                }).show();
            }
            else {
                $(ip_overlay).fadeTo('slow', 0.8);
            }

            // Set tabindex="-1" to content

            $('a, input, textarea, select, button').not('.close').each(function(){
                $(this).addClass('tabindex').attr('tabindex', '-1');
            });

            // Get popup size from rel attribut

            var popupHeight     = this.rel.split(',')[1],
                popupWidth      = this.rel.split(',')[0];

            if (popupWidth == null || popupHeight == null) {
                popupWidth      = settings.width;
                popupHeight     = settings.height;
            }

            // Set popup size

            var NormalCSS = {
                'bottom'        : 'auto',
                'height'        : popupHeight + 'px',
                'left'          : '50%',
                'margin-left'   : Math.floor(-(popupWidth)/2) + 'px',
                'margin-top'    : Math.floor(-(popupHeight)/2) + 'px',
                'max-height'    : popupHeight + 'px',
                'top'           : '50%',
                'width'         : popupWidth + 'px'
            };

            var FlexibleCSS = {
                'bottom'        : settings.margin + 'px',
                'height'        : 'auto',
                'margin-top'    : 0,
                'top'           : settings.margin + 'px'
            };

            // Normal iframe popup size

            $(ip_popup).css(NormalCSS).show();

            // Flexible iframe popup size

            $(window).resize(function(){
                ($(this).height() <= ($(ip_popup).outerHeight()+2*settings.margin)) ? $(ip_popup).css(FlexibleCSS) : $(ip_popup).css(NormalCSS);
            });

            ($(window).height() <= ($(ip_popup).outerHeight()+2*settings.margin)) ? $(ip_popup).css(FlexibleCSS) : $(ip_popup).css(NormalCSS);

            // Insert iframe title

            $(ip_title).html(this.title);

            // Insert iframe content

            $(ip_popup).addClass('ip_loading');
            $(ip_iframe).attr('src', this); 

            // Preloader

            $(ip_iframe).css('visibility', 'hidden');

            $(ip_iframe).load(function(){
                $(ip_popup).removeClass('ip_loading');
                $(ip_iframe).css('visibility', 'visible');
            });

            $(document).bind('keydown', keyDown);

            return false;
        });

        // Close popup

        function closeIframePopup(){

            $('body').css('overflow', bodyOverflow);
            $('html').css('overflow', htmlOverflow);
            $(ip_popup).hide();
            $(ip_overlay).fadeOut('slow');
            $(window).unbind('resize');

            // Remove tabindex="-1"

            $('.tabindex').each(function(){
                $(this).removeClass('tabindex').removeAttr('tabindex');
            });

        }

        // Keyboard events

        function keyDown(event){
            var code = event.keyCode;
            return ($.inArray(code, [27,88,67]) >= 0) ? closeIframePopup() : true;
        }

        // Create iframe popup

        function createIframePopup(){
            $('body').append(
                ip_overlay = $('<div>').attr({ 'class': 'ip_overlay' }).hide().click(closeIframePopup),
                ip_popup = $('<div class>').attr({ 'class': 'ip_popup' }).append(
                    ip_close = $('<a>').attr({ 'class': 'close', href: '#', title: close+' [ESC]' }).text(close).click(closeIframePopup),
                    ip_title = $('<h2>').attr({ 'class': 'title' }),
                    $('<div>').attr({ 'class': 'ip_content' }).append(
                        ip_iframe = $('<iframe>').attr({ 'src': '', 'frameborder': '0' })
                    )
                ).hide()
            );
            $([
                bodyOverflow = $('body').css('overflow'),
                htmlOverflow = $('html').css('overflow')
            ])
        }

        // Check hash and open popup

        var hash = location.hash;

        if (hash) {
            $(hash).click();
        }

    };
})(jQuery);

