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

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

        // No inline popup on smartphones etc.

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

        settings = $.extend({
            'margin'     : 40,           // Popup margin
            'content'    : 'iframe',     // iframe | image
            'opacity'    : 0.8,         // Opacity from overlay
            'show_title' : true         // Show title
        }, settings);

        // Create popup

        all_content  = this;
        $.fn.popup.create(all_content, settings);

        // Save css

        bodyOverflow      = $('body').css('overflow');
        htmlOverflow      = $('html').css('overflow');
        popup_height      = $('.lb_popup.image').height();
        popup_width       = $('.lb_popup.image').width()
        popup_margin_left = $('.lb_popup.image').css('margin-left');
        popup_margin_top  = $('.lb_popup.image').css('margin-top');

        return all_content.each(function() {

            var content = this;

            // Open popup

            $(content).click(function() {

                // Close popup

                var pos = $(window).scrollTop();

                $('.lb_close, .lb_overlay').unbind('click').click(function() {
                    $.fn.popup.close(pos, settings);
                });

                // Shortcuts

                $.fn.popup.shortcuts();

                // Resize popup image

                if (settings.content == 'image') {
                    $(window).resize(function() {
                        $.fn.popup.resize(settings, 1);
                    });
                }
                
                $(content).css('outline', 0); // Opera bug

                // Hide scrollbar

                if (settings.content == 'iframe')
                    $('body, html').css('overflow', 'hidden');

                // Load content

                if (!location.hash && settings.content == 'iframe') {

                    // Set hash if exist id

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

                    // Fadein overlay

                    $('.lb_overlay').fadeTo('slow', 0.8, function() {
                        $.fn.popup.load(content, settings);
                    });

                }
                else {
                    $('.lb_overlay').css('opacity', settings.opacity).show();
                    $.fn.popup.load(content, settings);
                }

                // Set tabindex="-1" to content

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

                return false;
            });

            // Check hash and open popup

            if (location.hash && settings.content == 'iframe') {
                $(location.hash).click();
            }

        });

    };

    // Load popup content

    $.fn.popup.load = function(content, settings) {

        if ($('.lb_popup').hasClass('animated')) return;

        // Content: image

        if (settings.content == 'image') {

            $('.lb_footer').hide();
            $('.lb_popup.image').show().addClass('animated'); // Animation started

            // Show loader

           $('.lb_image_load').show();

            // Load image

            var img_id = $(content).attr('id');
            $('.lb_content.image img').hide();

            if (!$('.lb_' + img_id).length) {
                var img = new Image();

                $('.lb_content.image').append(
                    $(img).attr('src', $(content).attr('href') + '?' + Math.random())
                );

                $(img).attr({
                    'alt'   : $(content).attr('title'),
                    'class' : 'lb_' + img_id
                }).load(function() {
                    $.fn.popup.animate(this, content, settings); // Animate
                });
            }
            else {
                $.fn.popup.animate($('.lb_' + img_id), content, settings); // Animate
            }
        }

        // Content: iframe

        if (settings.content == 'iframe') {

            // Get popup size from rel attribut

            var popupHeight = content.rel.split(',')[1],
                popupWidth  = content.rel.split(',')[0],
                popup_h     = $('.lb_popup.iframe').outerHeight() - $('.lb_popup.iframe').height(),
                popup_v     = $('.lb_popup.iframe').outerWidth() - $('.lb_popup.iframe').width();

            // Set popup size

            var NormalCSS = '';

            if (popupHeight != '') {
                NormalCSS = {
                    'bottom'        : 'auto',
                    'height'        : popupHeight + 'px',
                    'left'          : '50%',
                    'margin-left'   : Math.floor(-((popupWidth ? parseInt(popupWidth) : 800) + popup_h) / 2) + 'px',
                    'margin-top'    : Math.floor(-(parseInt(popupHeight) + popup_v) / 2) + 'px',
                    'max-height'    : popupHeight + 'px',
                    'top'           : '50%',
                    'width'         : (popupWidth ? popupWidth : 800) + 'px'
                };
            }

            var FlexibleCSS = {
                'bottom'        : settings.margin + 'px',
                'height'        : 'auto',
                'margin-left'   : Math.floor(-((popupWidth ? parseInt(popupWidth) : 800) + popup_h) / 2) + 'px',
                'margin-top'    : 0,
                'top'           : settings.margin + 'px',
                'width'         : (popupWidth ? popupWidth : 800) + 'px'
            };

            // Normal iframe popup size

            $('.lb_popup.iframe').css(NormalCSS ? NormalCSS : FlexibleCSS).show();

            // Flexible iframe popup size

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

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

            // Insert iframe title

            $('.lb_title').html($(content).attr('title'));

            // Insert iframe content

            $('.lb_popup.iframe').addClass('lb_iframe_load');
            $('.lb_iframe').attr('src', content.href);

            // Preloader

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

            $('.lb_iframe').load(function() {
                $('.lb_close, .lb_title, .lb_iframe').show();
                $('.lb_popup.iframe').removeClass('lb_iframe_load');
                $('.lb_iframe').css('visibility', 'visible');
            });

        }

    };

    // Animate popup

    $.fn.popup.animate = function(image, content, settings) {

        // Footer: title

        $('.lb_desc_title').empty();

        var title = $(image).attr('alt');

        if (!$('.lb_desc_title').length && title && settings.show_title) {
            $('.lb_desc').prepend(
                $('<div class="lb_desc_title">' + title + '</div>')
            );
        }
        else if (title) {
            $('.lb_desc_title').text(title);
        }

        // Footer: count

        if ($('.lb_count').length) {
            $('.lb_count').text(saved_count.replace('{x}', $(all_content).index($(content)) + 1));
        }

        // Resize image only

        $('.lb_popup.image img.active').removeClass('active');
        $(image).addClass('active');
        $.fn.popup.resize(settings, 0);
        $(image).hide();

        // Animate

        var image_height    = $(image).height(),
            image_width     = $(image).width();

        $('.lb_footer').css('width', image_width);

        var footer_height   = $('.lb_footer').outerHeight(),
            popup_h         = $('.lb_popup.image').outerHeight() - $('.lb_popup.image').height(),
            popup_v         = $('.lb_popup.image').outerWidth() - $('.lb_popup.image').width();

        $.fn.popup.menu(content, settings);

        $('.lb_popup.image').animate({
            'height'        : image_height,
            'margin-left'   : Math.floor(-((image_width + popup_v) / 2)),
            'margin-top'    : Math.floor(-((image_height + footer_height + popup_h) / 2)),
            'width'         : image_width
        }, 500, function() {
            $(image).fadeIn(500, function() {
                $('.lb_popup.image').animate({
                    'height' : image_height + footer_height
                }, 500, function() {
                    $('.lb_footer').fadeIn(500, function() {
                        $('.lb_close').show();
                        $('.lb_footer').css('width', 'auto');
                        $('.lb_popup.image').removeClass('animated'); // Animation finished
                    });
                });
                $('.lb_image_load').hide(); // Hide loader
            });
        }).addClass('animated image');

    };

    // Shortcuts

    $.fn.popup.shortcuts = function() {
        $(document).bind('keydown', function(event) {
            if (event.keyCode == 27) // Escape
                $('.lb_close').click();
            if (event.keyCode == 39) // Next
                $('.lb_next').click();
            if (event.keyCode == 37) // Previous
                $('.lb_prev').click();
        });
    }

    // Menu

    $.fn.popup.menu = function(content, settings) {

        var index = $(all_content).index($(content)),
            all   = $(all_content).length,
            prev  = index - 1 < 0 ? all - 1 : index - 1,
            next  = index + 1 >= all ? 0 : index + 1;

        $('.lb_next').unbind().click(function() {
            $.fn.popup.load($(all_content)[next], settings);
        });
        $('.lb_prev').unbind().click(function() {
            $.fn.popup.load($(all_content)[prev], settings);
        });
    };

    // Resize window

    $.fn.popup.resize = function(settings, resize_popup) {
        if(resize_popup && ($('.lb_popup.image').hasClass('animated') || !$('.lb_popup.image').is(':visible')) || !$('.lb_popup.image img.active').length)
            return;

        var lb_popup    = $('.lb_popup.image')[0],
            lb_popupimg = $('.lb_popup.image img.active')[0],
            popup_h     = $('.lb_popup.image').outerHeight() - $('.lb_popup.image').height(),
            popup_v     = $('.lb_popup.image').outerWidth() - $('.lb_popup.image').width();

        if (!lb_popupimg.original_height) {
            lb_popupimg.original_height       = lb_popupimg.offsetHeight;
            lb_popupimg.original_width        = lb_popupimg.offsetWidth;
            lb_popupimg.original_popup_height = $(lb_popup).outerHeight();
            lb_popupimg.original_popup_width  = $(lb_popup).outerWidth();
        }

        var max_height = lb_popupimg.original_height + 100 + (settings.margin * 2);

        if ($(window).height() <= max_height) {

            $('.lb_desc_title').hide(); // Hide description on resized image

            var window_height = $(window).height() >= 600 ? $(window).height() : 600,
                new_height    = window_height - (max_height - lb_popupimg.original_height);

            new_height = new_height > 0 ? new_height : 1;
            $('.lb_popup.image img.active').height(new_height);

            var new_popup_height = new_height + $('.lb_footer').outerHeight();
                new_popup_width  = $('.lb_popup.image img.active').outerWidth();

            // Resize popup

            if(resize_popup) {
                $('.lb_popup.image').css({
                    'height'      : new_popup_height,
                    'margin-top'  : Math.floor(-((new_popup_height + popup_h) / 2)),
                    'width'       : new_popup_width,
                    'margin-left' : Math.floor(-((new_popup_width + popup_v) / 2))
                });
            }
        }
        else {

            $('.lb_desc_title').show(); // Show description on original image size

            $('.lb_popup.image img.active').height(lb_popupimg.original_height);

            var new_popup_height = lb_popupimg.original_height + $('.lb_footer').outerHeight(),
                new_popup_width  = $('.lb_popup.image img.active').outerWidth();

            if(resize_popup) {
                $('.lb_popup.image').css({
                    'height'      : new_popup_height,
                    'margin-top'  : Math.floor(-((new_popup_height + popup_h) / 2)),
                    'width'       : new_popup_width,
                    'margin-left' : Math.floor(-((new_popup_width + popup_v) / 2))
                });
            }
        }

    };

    // Create popup

    $.fn.popup.create = function(all_content, settings) {

        if (!$('.lb_overlay').length) {
            $('body').append(
                $('<div class="lb_overlay" />').hide()
            );
        }

        // Create iframe container

        if (settings.content == 'iframe' && !$('.lb_popup.iframe').length) {
            $('body').append(
                $('<div class="lb_popup iframe" />').append(
                    $('<a class="lb_close" href="javascript:void(0)" title="' + close + ' [ESC]">' + close + '</a>').hide(),
                    $('<strong class="lb_title" />').hide(),
                    $('<div class="lb_content iframe" />').append(
                        $('<iframe class="lb_iframe" src="" frameborder="0" />').hide()
                    )
                ).hide()
            );
        }

        // Create image container

        if (settings.content == 'image' && !$('.lb_popup.image').length) {

            var images = $(all_content).length;

            $('body').append(
                $('<div class="lb_popup image" />').append(
                    lb_content = $('<div class="lb_content image" />'),
                    $('<div class="lb_image_load" />').hide(),
                    $('<div class="clearfix lb_footer" />').append(
                        lb_desc = $('<div class="lb_desc" />'),
                        $('<a class="lb_close" href="javascript:void(0)" title="' + close + ' [ESC]">' + close + '</a>').hide()
                    ).hide()
                ).hide()
            );

            saved_count = count.replace('{y}', images);

            if (images > 1) {
                lb_content.append(
                    $('<a class="lb_prev lb_nav" href="javascript:void(0)" title="' + prev_image + ' [&#171;]"><span>' + prev_image + '</span></a>'),
                    $('<a class="lb_next lb_nav" href="javascript:void(0)" title="' + next_image + ' [&#187;]"><span>' + next_image + '</span></a>')
                )
                lb_desc.append(
                    $('<div class="lb_count">' + saved_count + '</div>')
                )
            }
        }

    };

    // Close popup

    $.fn.popup.close = function(pos, settings) {

        if ($('.lb_popup').hasClass('animated') || !$('.lb_popup').is(':visible')) return;

        if (settings.content == 'image') {

            // Hide and reset popup

            $('.lb_popup').stop().css({
                'height'      : popup_height,
                'margin-left' : popup_margin_left,
                'margin-top'  : popup_margin_top,
                'width'       : popup_width
            });

            $('.lb_footer, .lb_close').hide();
            $('.lb_count').text(saved_count);
        }

        if (settings.content == 'iframe') {

            // Reset to default

            $('body').css('overflow', bodyOverflow);
            $('html').css('overflow', htmlOverflow);

            location.hash = '';

            $('html, body').scrollTop(pos);

        }

        $('.lb_popup, .lb_close, .lb_title, .lb_iframe').hide();
        $('.lb_overlay').fadeOut(500);

        // Unbind shortcuts and resize

        $(document).unbind('keydown');
        $(window).unbind('resize');

        // Remove tabindex="-1"

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

        return false;
    }

})(jQuery);

