 /**
  * @name       ajaxLightbox
  * @version    1.0.5
  *
  * CHANGES:
  *
  * 1.0.5 (2011-10-05)
  * - Reposition lightbox after window resize, while retaining the visible position of the lightbox
  *
  * 1.0.4 (2010-11-10)
  * 
  *
  * 1.0.3 (2010-11-09)
  * - CSS included in JS
  * - Options added to centerX or centerY, or fixed positioning
  *
  * 1.0.2 (2010-08-03)
  * - Multiple instances of lightbox possible
  *
  * 1.0.1 (2010-06-01)
  * - Clicking on overlay, closes the lightbox
  * - Fix to resize overlay to 100% of window when html is smaller than window height
  *
  *
  * TODO:
  * - Option to load JSON content instead of pure HTML
  *
  * This work is licensed under the Creative Commons Attribution-Share Alike 2.0 Belgium License.
  * To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.0/be/.
  *
  *
  * @author     Davy De Pauw (http://www.float.be)
  * @example    $('body').lightbox({ closeLabel: 'close', overlayColor: '#000' });
  *
  */
(function($) {

    var $overlay, $lb, $html, $this;

    $.fn.ajaxLightbox = function(options)
    {
        // Cache the html element
        $html = $('html');

        return this.each(function() {

            // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
            $(this).unbind('click').click(function(e) {

                e.preventDefault();

                // Set options
                this.opts = $.extend({}, $.fn.ajaxLightbox.defaults, options);

                // Narrow option
                if($(this).hasClass('narrow')) this.opts.size = 'narrow';

                // Init lightbox
                init(this);
            });
        });
    };

    function init(el)
    {
        render(el);

        show(el);

        return false; // Avoid the browser following the link
    };

    function render(el)
    {
        // Create overlay instance
        $overlay = $('<div id="overlay"></div>');

        var className = '';
        
        if(el.opts.size != '') className = ' ' + el.opts.size;

        // Create lightbox instance
        $lb = $('<div class="lightbox' + className + '" id="lightbox" role="dialog" aria-labeledby="lightbox-header"><div class="inner"></div></div>');

        // Set styling for lightbox
        $lb.css({
            position: 'absolute',
            zIndex: 200
        });

        if(el.opts.closeButton)
        {
            // Create close button
            $close = $('<a href="" class="close" id="lightbox-close">' + el.opts.closeLabel + '</a>');
    
            // Attach button to lightbox
            $lb.append($close);
    
            $close.click(function(e) {
                remove();
                e.preventDefault();
            });
        };

        var view = getViewportInfo();

        // Set styling
        $overlay.css({
            position: 'absolute',
            top: 0,
            left: 0,
            float: 'left',
            opacity: el.opts.overlayOpacity,
            width: getClientWidth(),
            height: view.scrollHeight,
            backgroundColor: el.opts.overlayColor,
            backgroundImage: el.opts.imagePath,
            backgroundRepeat: 'repeat',            
            backgroundPosition: '0 0',
            zIndex:	100
        })
        .click(function(e) {
            remove();
        });

        // Append
        $('body').append($lb);
        $('body').append($overlay);
        
        $(window).resize(function(e) {
        
            $overlay.css({
                width: getClientWidth(),
                height: view.scrollHeight
            });
            
            position(el);
        
        });
    };

    function show(el)
    {
        if(el.opts.redirect)
        {
            href = el.opts.redirect;
        }
        else
        {
            href = el.getAttribute('href');
        }

        // Needs to perform an ajax call to display content?
        if(el.opts.ajaxEnabled)
        {
            // Load AJAX result into lightbox
            $.get(href, function(data) {
    
                var $inner = $lb.find('.inner');
                
                // Populate lightbox with html from result
                $inner.html(data);
    
                $lb.find('a.close').click(function(e) {
                    remove();
                    e.preventDefault();
                });
    
                position(el);
                
                // Set required indicators if necessary
                application.forms.setRequiredFieldIndicators($inner);
                
                // run callback
                el.opts.callback();
            });
        }
        
        // Clone the content to be displayed (based on the #id)
        else
        {
            // Make sure the hash value of the link is used, because IE7 will use the full url when the href attr is called
            $lb.find('.inner').html($(el.hash).html());
            
            position(el);
        }

        $('body').addClass('hideSelects');
    };

    function remove()
    {
        // Hide lightbox
        $lb.remove();
        $overlay.remove();

        $('body').removeClass('hideSelects');
    };

    function position(el)
    {
        var windowHeight = getHeight(),
            windowTop = getTop(),
            lbHeight = $lb.outerHeight();
                
        // Center horizontally, but only if lightbox height is smaller than windowheight
        if(el.opts.centerY && windowHeight > (lbHeight + (el.opts.top * 2))) $lb.css('top', windowTop + (windowHeight / 2) - lbHeight / 2);
        else $lb.css('top', el.opts.top);
                
        // Center vertically
        if(el.opts.centerX) $lb.css('left', $html.width()/2 - $lb.width()/2);
        
		// Show the lightbox
		$lb.show();
    };

    function getTop() {
        return window.pageYOffset || document.documentElement && document.documentElement.scrollTop ||  document.body.scrollTop;
    };

    function getHeight() {
        return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight;
    };

    /**
     * Get the viewport info. Contains size and scroll offsets.
     *
     * @returns {Object} with the width and height
     */
    function getViewportInfo() {
        // W3C compliant, or fallback to body
        var root = (document.documentElement && document.compatMode == 'CSS1Compat')
            ? document.documentElement
            : document.body;
        
        return {
            // Fix for Chrome (see: http://code.google.com/p/chromium/issues/detail?id=2891)
            scrollTop    : Math.max(document.body.scrollTop, document.documentElement.scrollTop),
            scrollLeft   : root.scrollLeft,
            width        : self.innerWidth  ? self.innerWidth  : root.clientWidth,
            height       : self.innerHeight ? self.innerHeight : root.clientHeight,
            scrollHeight : root.scrollHeight
        };
    };

    function getClientHeight() {

        // Page height
        var h = getHeight();

        // Check if body height is 100% (so page height < body height)
        if(h < document.body.offsetHeight) return document.body.offsetHeight;

        // Else use the window height
        else return h;
    };

    function getClientWidth() {
        return document.body.offsetWidth;
    };

	// Set defaults
    $.fn.ajaxLightbox.defaults = {
    
        // AJAX enabled
        ajaxEnabled: true,

        // Translation labels
        closeLabel: 'sluiten',
        closeButton: false,

        // Overlay
        overlayColor: '#000',
        overlayOpacity: 0.5,
        
        // Center axis
        centerX: true,
        centerY: true,
        
        size: '',
        
        // Top offset (if centerY == false)
        top: 40,
        
        callback: function(){},
        
        imagePath: 'url(../1.0.0/img/bg_spacer.png)'
    };

}) (jQuery);
