document.lightbox = {
    locked:       false,
    overlay:      null,
    outer:        null,
    inner:        null,
    closeButton:  null,
    throbber:     null,
    events:       {},
    entrance:     {},

    init: function() {
        if($('a[rel]').length == 0) {
            return;
        }

        this.createStructure();
        this.attachObservers();
        this.executeEvents('post-init');

        this.entrance.visibility = document.lightbox.visible();
        this.entrance.page       = window.location.pathname;
        this.entrance.hash       = window.location.hash;

        if (window.location.hash == '#/?rel=lightbox' || window.location.hash == '#/?rel=lightbox-left' || window.location.hash == '#/?rel=lightbox-right') {
            window.location.hash = '';
        }

        var historySupport = false;
        // Browsers that support HTML5 History
        if (jQuery.browser.webkit &&
                (navigator.userAgent.toLowerCase().indexOf('chrome') > -1 /* Chrome, all versions */ ||
                (navigator.userAgent.toLowerCase().indexOf('safari') > -1 && navigator.userAgent.toLowerCase().indexOf('version/5') > -1) /* Safari >= 5 */)
           ) {
            historySupport = true;
        } else if(jQuery.browser.mozilla) {
            version = navigator.userAgent.toLowerCase().match(/firefox\/(\d)/);
            if(version != null && version >= 4) {
                historySupport = true;
            }
        }

        $.address.state(historySupport ? '/' : this.entrance.page)
                 .autoUpdate(false)
                 .change(function(event) {
                     // Situation 1: Close button clicked: see this.attachObservers()
                     if(typeof(event.parameters.action) != 'undefined' && event.parameters.action == 'close') {
                        document.lightbox.hide();
                        document.lightbox.attachObservers
                     }
                     // Situation 2: Backbutton pressed (probably)
                     else if((document.lightbox.entrance.page == event.value || event.value == '/') && document.lightbox.visible() && document.lightbox.entrance.visibility === false) {
                        document.lightbox.hide();
                     }
                     // Situation 3: HTML5-History users (url replaced), backbutton was presses (propably), lightbox was opened on entrance. Go back to first screen.
                     else if(historySupport && document.lightbox.entrance.page == event.value && document.lightbox.entrance.visibility === true) {
                         parameters = {'modal': '1', 'part': '0'};

                         document.lightbox.loadUrl('lightbox', document.lightbox.entrance.page, 'get', parameters);
                     }
                     // Situation 4: normal clicks on anchors.
                     else if(typeof(event.parameters.rel) != 'undefined') {
                         parameters = {'modal': '1'};

                         // Insert whole lightbox (no partial) if lightbox is not visible
                         if ((event.parameters.rel != 'lightbox-left' && event.parameters.rel != 'lightbox-right') || !document.lightbox.visible()) {
                             parameters.part      = '0';
                             event.parameters.rel = 'lightbox';
                         }

                         document.lightbox.loadUrl(event.parameters.rel, event.value, 'get', parameters);
                     }
                     // Situation 5: Non-HTML5-History (hash navigation), backbutton was presses (probably), lightbox was opened on entrance. Go back to first screen.
                     else if(!historySupport && document.lightbox.entrance.page == window.location.pathname && document.lightbox.entrance.hash == window.location.hash && document.lightbox.entrance.visibility === true) {
                         parameters = {'modal': '1', 'part': '0'};

                         document.lightbox.loadUrl('lightbox', document.lightbox.entrance.page, 'get', parameters);
                     }

                     return false;
                 });
    },

    loadUrl: function(target, url, method, parameters) {
        if (this.locked) return;

        this.locked = true;

        if (! method)     method = 'get';
        if (! parameters) parameters = {'modal': '1'};

        this.showThrobber();
        this.show();

        $.ajax({
            url: url,
            dataType: 'html',
            type: method,
            data: parameters,
            complete: function(transport) {
                document.lightbox.setContent(target, transport.responseText);
                document.lightbox.attachObservers();
                document.lightbox.executeEvents('post-load');
                document.lightbox.historySave(url);
                document.lightbox.hideThrobber();
                document.lightbox.locked = false;

                if (window.pageTracker) {
                    window.pageTracker._trackPageview(url);
                }
            }
        });
    },

    historySave: function(url) {

    },

    historyLoad: function() {

    },

    attachObservers: function() {
        // Remove live()-observers, to prevent them to be set twice
        $('a[rel]').die();

        $('a[rel]').live('mousedown', function(event) {
            if (event.which != 1) return;

            $.address.value($(this).attr('href').replace('http://' + document.domain, ''))
                             .parameter('rel', $(this).attr('rel'))
                             .update();
            return false;
        });

        $('a[rel]').live('click', function(event) { return false });

        if ($('#lightbox-closebutton').length != 0) {
            if (this.closeButton === null) this.closeButton = $('#lightbox-closebutton');

            $(this.closeButton).parent().unbind('click')
                                        .unbind('mousedown');
            $(this.closeButton).parent().click(function() { return false; });
            $(this.closeButton).parent().mousedown(function(event) {
                // event.which = 1 = left mouse click
                if (event.which != 1) return;

                if(document.lightbox.entrance.visibility) {
                    // Using '/' as a url doesn't work in any browser but Chrome, don't know why
                    $.address.value(navigator.userAgent.toLowerCase().indexOf('chrome') > -1 ? '/' : '/index.php')
                             .parameter('action', 'close')
                             .update();
                } else {
                    $.address.parameter('action', 'close')
                             .value(document.lightbox.entrance.page)
                             .update();
                }

                return false;
            });
        }
    },

    createStructure: function() {
        this.outer = ($('#lightbox-outer').length == 1)
            ? $('#lightbox-outer')
            : $('<div></div>').attr('id','lightbox-outer');

        this.inner = ($('#lightbox-inner').length == 1)
            ? $('#lightbox-inner')
            : $('<div></div>').attr('id','lightbox-inner');

        this.overlay = ($('#lightbox-overlay').length == 1)
            ? $('#lightbox-overlay')
            : $('<div></div>').attr('id','lightbox-overlay')
                              .hide();

        var body = $('body');

        if($(this.outer).find(this.inner).length == 0)   $(this.inner).appendTo($(this.outer));
        if($(this.overlay).find(this.outer).length == 0) $(this.outer).appendTo($(this.overlay));
        if($(body).find(this.overlay).length == 0)       $(this.overlay).appendTo($(body));
    },

    createCloseButton: function() {
        this.closeButton = ($('#lightbox-closebutton').length == 1)
            ? $('#lightbox-closebutton')
            : $('<img>').attr('id', 'lightbox-closebutton')
                        .attr('src', '/media/images/layout/lightbox-close.png');

        if (! $(this.inner).find($(this.closeButton))) $(this.inner).prepend(this.closeButton);
    },

    showThrobber: function() {
        if (! this.throbber) {
            this.throbber = ($('#lightbox-throbber').length == 1)
                ? $('#lightbox-throbber')
                : $('<img />').attr('id', 'lightbox-throbber')
                            .attr('src', '/media/images/layout/throbber.gif');
        }

        if ($(this.overlay).find(this.throbber).length == 0) $(this.overlay).append(this.throbber);

        $(this.throbber).show();
    },

    hideThrobber: function() {
        if (! this.throbber) return;

        $(this.throbber).hide();
    },

    setContent: function(target, content) {
        if (target == 'lightbox') {
            $(this.inner).html(content);
        } else {
            $('#' + target).html(content);
        }

        this.createCloseButton();
    },

    visible: function() {
        return $(this.overlay).is(':visible');
    },

    show: function() {
        $(this.overlay).show();
        $('html').css('overflowY', 'hidden');
        this.executeEvents('post-show');
    },

    hide: function() {
        $(document.lightbox.overlay).hide();
        $(document.lightbox.inner).html('');
        $('html').css('overflowY', 'scroll');
        document.lightbox.executeEvents('post-hide');
    },

    attachEvent: function(hookName, callback) {
        if (! this.events[hookName]) this.events[hookName] = [];

        this.events[hookName][this.events[hookName].length] = callback;
    },

    executeEvents: function(hookName) {
        if (! this.events[hookName]) return;

        $(this.events[hookName]).each(function(i, callback) {callback();});
    }
};

$(document).ready(function() {
    document.lightbox.init();
});
