﻿/*
UNIVERSAL LIGHTBOX
By Ben, July 19-20 2011
Requires jQuery 1.5.0 or better 

User guide
Add a css class of "lightbox" to the element containing the lighbox and class "opener" to any click to open controls
Basic behaviour: add a child element with a class of "content" - all html in this element will be rendered

Styling: any classes added to the element classed "lightbox" will be used when the lightbox opens
To directly reference/override this, use css class of '#LightboxShell .[className] {[css]}'
To style the background layer (colour, opacity etc.), use css class of '#LightboxBackground {[css]}'

The following classes are reserved for lightbox functionality - when applied to the "lightbox"-classed element:
"floating" - lightbox can be positioned where required (defaults fixed to centre)
"noBackground" - no background is displayed

Elements in the lightbox content classed as "closer" will close the lightbox. If none is provided in the content,
the lightbox will automatically have one added

*/

$(document).ready(function () {
    if ($('.lightbox')) {
        $('.lightbox').AttachLightboxes();
    }
});

(function ($) {
    $.fn.AttachLightboxes = function () {

        var SourceObject;

        AttachLightboxCss();

        AddShellIfNodeExists('#Body');

        if ($('.lightbox.imagePresenter').length > 0) {
            AttachOpenersIfRequired($('.lightbox.imagePresenter'));
        }

        return this.each(function () {
            SourceObject = $(this)[0];

            WireUpOpeners();
        });

        function WireUpOpeners() {
            $('.opener', SourceObject).click(function (e) {
                e.preventDefault();

                SourceObject = $(this).parents('.lightbox')[0];

                // Handle the various behaviours
                // TODO: Add other behaviours here, based on the presence of given classes
                // "CopyContentToLightbox" should be the final "else" clause

                if ($(SourceObject).hasClass('veryLargeImage')) {
                    VeryLargeImageLightbox(SourceObject)
                }
                else {
                    CopyContentToLightbox(SourceObject);
                }

                // Set the classes we want to attach
                SetLightboxShellClasses($(SourceObject).attr('class'));

                // Additional presentation - fix to centre, switch background on/off
                if (!($(SourceObject).hasClass('floating'))) {
                    SetCentredBySizes();
                }

                if (!($(SourceObject).hasClass('noBackground'))) {
                    DisplayBackground();
                }

                // Attach events to close boxes etc.
                WireUpClosers();
            });
        }
    };
})(jQuery);

// Attach control CSS classes for the lightbox
function AttachLightboxCss()
{
    $('head').after('<style type="text/css">#LightboxShell {z-index: 2001;}#LightboxShell, #LightboxBackground, .lightbox .content {display: none;}#LightboxShell.visible {display: block; }#LightboxBackground.visible {display: block; z-index: 1500; position: fixed; top: 0; left: 0;}#LightboxShell span.attached {position: absolute; top: 0; left: 0; text-align: right;}#LightboxShell span.attached .closer {font-weight: bold; padding: 5px; cursor: pointer;}#LightboxBackground {background: #DDDDDD; opacity:0.7; filter:alpha(opacity=70);  -moz-opacity:0.7;} </style>');
}

// Add lightbox display nodes to a given element's HTML if the element exists and the display nodes are not already present
function AddShellIfNodeExists(NodeID) {
    if ($(NodeID).length > 0) {
        if ($('#LightboxShell').length < 1) {
            $(NodeID).after('<div id="LightboxShell"></div>');
        }
        if ($('#LightboxBackground').length < 1) {
            $(NodeID).after('<div id="LightboxBackground"></div>');
        }
    }
}

// Attach opener to a lightbox-classed element if not already present
function AttachOpenersIfRequired(SourceObject) {
    if ($('.opener',SourceObject).length < 1) {
        $(SourceObject).css({'position' : 'relative'});
        $(SourceObject).prepend('<span class="opener" style="position: absolute; cursor: pointer;"></span>');
    }
}

// Attach closer to the content of a displayed lightbox if not already present
function AttachCloser() {
    $('#LightboxShell').prepend('<span class="attached"><span class="closer">[X]</span></span>');
}

// Locate a child of the .lightbox-class element with a class of .content and copy the inner HTML of that child element into the display node
function CopyContentToLightbox(SourceObject) {
    // Transfer the html
    $('#LightboxShell').html($('.content', SourceObject).html());

    // Force attachment of a closer if we do not have one...
    if ($('#LightboxShell .closer').length < 1) {
        AttachCloser();
        $('#LightboxShell .attached').css('width',$('.content', SourceObject).css('width'));
    }
}

// Set the content of the display node to a "very large" image based on the src of the first img child node of the .lightbox-classed element
function VeryLargeImageLightbox(SourceObject) {
    if ($('img',SourceObject).length > 0) {
        // Get the path and filename of the "very large" image
        var imagePath = $(location).attr('href').replace(window.location.pathname, '') + '/images/products/verylarge/';
        var imageFile = $($('img',SourceObject)[0]).attr('src').split('/')[$($('img',SourceObject)[0]).attr('src').split('/').length - 1];

        // Set the html of the lightbox shell
        $('#LightboxShell').html('<img src="' + imagePath + imageFile + '" onerror="this.src=\'' + $($('img',SourceObject)[0]).attr('src') + '\'" />');
        $('#LightboxShell').css({'text-align' : 'center'});

        // Force attachment of a closer if we do not have one...
        if ($('#LightboxShell .closer').length < 1) {
            AttachCloser();
            $('#LightboxShell .attached').css('right','0');
        }
    }
}

function SetLightboxShellClasses(SourceClassList) {

    var ReservedClasses = 'lightbox,visible,addCloser,noBackground,floating,imagePresenter';

    for (var i in ReservedClasses.split(',')) {
        SourceClassList = SourceClassList.replace(i, '');
    }

    // Remove the existing classes from the display area and add our own
    $('#LightboxShell').removeClass($('#LightboxShell').attr('class')).addClass('visible ' + SourceClassList);
}

function WireUpClosers() {
    $('#LightboxShell .closer').click(function (e) {

        // Prevent default action
        e.preventDefault();

        $('#LightboxShell').removeClass('visible');
        $('#LightboxBackground').removeClass('visible');
    });
}

function SetCentredBySizes() {
    var Left = ($(window).width() - $('#LightboxShell').width()) / 2;
    var Top = ($(window).height() - $('#LightboxShell').height()) / 2;

    $('#LightboxShell').css({
        'position': 'fixed',
        'top': Top + 'px',
        'left': Left + 'px'
    });
}

function DisplayBackground() {
    $('#LightboxBackground').css({
        'width': $(window).width() + 'px',
        'height': $(window).height() + 'px'
    });

    $('#LightboxBackground').addClass('visible');
}

