var lightboxUrl = null;
var lightboxContentElement = null;
var lightboxWidth = 300;
var lightboxHeight = 300;
var lightboxCenterPosX = 0; 
var lightboxCenterPosY = 0;
var lightboxStartPosX = 0;
var lightboxStartPosY = 0;
var lightboxStartWidth = 0;
var lightboxStartHeight = 0;
var lightboxLoadingMessage = '';
var lightboxLoadingErrorMessage = 'Temporary error';
var lightboxOnCloseFunction = null;
var lightboxInitialized = false;

Event.observe(window, 'load', initLightBox);

function initLightBox() {
    // Add clearer element to make sure body height can be calculated correctly
    var lightBoxBodyClearer = new Element('div');
    document.body.appendChild(lightBoxBodyClearer);

    var lightboxOverlay = new Element('div', {'id': 'lightboxOverlay', 'style': 'position:fixed'});
    lightboxOverlay.hide();
    Event.observe(lightboxOverlay, 'click', hideLightbox);
    document.body.appendChild(lightboxOverlay);

    var lightbox = new Element('div', {'id': 'lightbox'});
    lightbox.hide();

    var lightboxHeader = new Element('div', {'id': 'lightboxHeader'});
    lightboxHeader.hide();

    var lightboxCloseLink = new Element('a', {'id': 'lightboxCloseLink', 'href': 'Javascript:hideLightbox();'});
    lightboxCloseLink.addClassName('close_popup'); // For some reason class/className cannot be added as an attribute in the line above when running (some versions of) IE8
    lightboxCloseLink.update("&nbsp;");
    lightboxHeader.appendChild(lightboxCloseLink);

    lightbox.appendChild(lightboxHeader);

    var lightboxBody = new Element('div', {'id': 'lightboxBody'});

    var lightboxContents = new Element('div', {'id': 'lightboxContents'});
    lightboxContents.hide();

    var lightboxLoadingScreen = new Element('div', {'id': 'lightboxLoadingScreen'});
    lightboxLoadingScreen.hide();
    var lightboxLoadingScreenMessage = new Element('p', {'id': 'lightboxLoadingScreenMessage'});

    lightboxLoadingScreen.appendChild(lightboxLoadingScreenMessage);

    lightboxBody.appendChild(lightboxContents);
    lightboxBody.appendChild(lightboxLoadingScreen);

    lightbox.appendChild(lightboxBody);

    document.body.appendChild(lightbox);

    Event.observe(window, 'resize', resizeLightboxOverlay);
    lightboxInitialized = true;
}

/**
 * @param paramsObject parameter object containing the following possible fields: 
 *      Required:
 *          width, height
 *      Optional :
 *          left, top,
 *          url, (url or contentElement is required)
 *          contentElement, (url or contentElement is required)
 *          startTemplate,
 *          startPosX, startPosY, startWidth, startHeight,
 *          startTemplate, loadingMessage, loadingErrorMessage,
 *          onCloseFunction
 */
function showLightbox(paramsObject) {
    if( !lightboxInitialized ) initLightBox();

    lightboxUrl = paramsObject.url;
    lightboxContentElement = paramsObject.contentElement;
    lightboxWidth = paramsObject.width;
    lightboxHeight = paramsObject.height;
    lightboxLoadingMessage = (typeof(paramsObject.loadingMessage) !== 'undefined' && paramsObject.loadingMessage != null) ? paramsObject.loadingMessage : lightboxLoadingMessage;
    lightboxLoadingErrorMessage = (typeof(paramsObject.loadingErrorMessage) !== 'undefined' && paramsObject.loadingErrorMessage != null) ? paramsObject.loadingErrorMessage : lightboxLoadingErrorMessage;

    var screenSize = getScreenSize();
    if( typeof(paramsObject.startTemplate) !== 'undefined' && paramsObject.startTemplate != null ) {
        paramsObject.startTemplate = $(paramsObject.startTemplate);
        var dim = Element.getDimensions(paramsObject.startTemplate);
        var pos = Element.positionedOffset(paramsObject.startTemplate);
        lightboxStartPosX = pos.left;
        lightboxStartPosY = pos.top;
        lightboxStartWidth = dim.width;
        lightboxStartHeight = dim.height;
    } else {
        lightboxStartPosX = (typeof(paramsObject.lightboxStartPosX) !== 'undefined' && paramsObject.lightboxStartPosX != null) ? paramsObject.lightboxStartPosX : screenSize.width / 2;
        lightboxStartPosY = (typeof(paramsObject.lightboxStartPosY) !== 'undefined' && paramsObject.lightboxStartPosY != null) ? paramsObject.lightboxStartPosY : screenSize.height / 2;
        lightboxStartWidth = 0;
        lightboxStartHeight = 0;
    }

    if( paramsObject.lightBoxClass !== 'undefined' && paramsObject.lightBoxClass != null ) $('lightbox').className = paramsObject.lightBoxClass;

    if( paramsObject.onCloseFunction !== 'undefined' && paramsObject.onCloseFunction != null ) lightboxOnCloseFunction = paramsObject.onCloseFunction;

    var screenSize = getScreenSize();
    if( (paramsObject.left !== 'undefined') && (paramsObject.left != null) && (paramsObject.left > 0)) {
        lightboxCenterPosX = paramsObject.left + lightboxWidth / 2;
    } else {
        lightboxCenterPosX = screenSize.width / 2;
    }
    if( (paramsObject.top !== 'undefined') && (paramsObject.top != null) && (paramsObject.top > 0)  ) {
        lightboxCenterPosY = paramsObject.top + lightboxHeight / 2 + getScrollY();
    } else {
        lightboxCenterPosY = screenSize.height / 2 + getScrollY();
    }

    if( lightboxLoadingMessage != '' ) {
        $('lightboxLoadingScreenMessage').update(lightboxLoadingMessage);
        $('lightboxLoadingScreen').show();
    }

    $('lightboxOverlay').setOpacity(0);
    $('lightboxOverlay').show();

    screenSize.height = Math.max(screenSize.height, Element.getDimensions(document.body).height);
    $('lightboxOverlay').setStyle({height: screenSize.height + 'px'});

    doShowLightbox1();
}

function doShowLightbox1() {
    //var screenSize = getScreenSize();
    var lightbox = $('lightbox');
    lightbox.style.width = lightboxStartWidth + 'px';
    lightbox.style.height = lightboxStartHeight + 'px';
    lightbox.style.top = lightboxStartPosY + 'px';
    lightbox.style.left = lightboxStartPosX + 'px';
    new Effect.Parallel([
        new Effect.Appear(lightbox, {sync: true}),
        //new Effect.Move(lightbox, {sync: true, x: ((screenSize.width / 2) - (Element.getDimensions('lightbox').width / 2)), y: ((screenSize.height / 2) - (Element.getDimensions('lightbox').height / 2)), mode: 'absolute'}),new Effect.Opacity('lightboxOverlay', { from: 0.0, to: 0.6})
        new Effect.Move(lightbox, {sync: true, x: (lightboxCenterPosX - (Element.getDimensions('lightbox').width / 2)), y: (lightboxCenterPosY - (Element.getDimensions('lightbox').height / 2)), mode: 'absolute'}),new Effect.Opacity('lightboxOverlay', { from: 0.0, to: 0.6})
    ], {
        duration: 0.6
    });
    setTimeout(doShowLightbox2, 600);
}

function doShowLightbox2() {
    //var screenSize = getScreenSize();
    new Effect.Tween($('lightbox'), Element.getDimensions('lightbox').width, lightboxWidth, {duration: 0.3 }, function(p) {
        this.style.width = p + 'px';
        //this.style.left = ((screenSize.width / 2) - p / 2) + 'px';
        this.style.left = (lightboxCenterPosX - p / 2) + 'px';
    });
    setTimeout(doShowLightbox3, 300);
}

function doShowLightbox3() {
    var screenSize = getScreenSize();
    new Effect.Tween($('lightbox'), Element.getDimensions('lightbox').height, lightboxHeight, {duration: 0.3 }, function(p) {
        this.style.height = p + 'px';
        //this.style.top = ((screenSize.height / 2) - p / 2) + 'px';
        this.style.top = (lightboxCenterPosY - p / 2) + 'px';
    });
    setTimeout(doShowLightbox4, 300);
}

function doShowLightbox4() {
    if( lightboxLoadingMessage != '' ) {
        Effect.Appear($('lightboxLoadingScreen'), {duration: 0.3});
    }
    Effect.Appear($('lightboxHeader'), {duration: 0.3});
    getLightboxContent()
}

function getLightboxContent() {
    // Fetch content via ajax call...
    if( (typeof(lightboxUrl) !== 'undefined' && lightboxUrl != null) ) {
        var ajaxStartTime = new Date().getTime();
        new Ajax.Request(lightboxUrl, {
            method: 'get',
            onSuccess: function(transport) {
                $('lightboxContents').update(transport.responseText);
                var delay = 0;
                if( lightboxLoadingMessage != '' ) {
                    delay = 500 - (new Date().getTime() - ajaxStartTime);
                    if( delay < 0 ) delay = 0;
                }
                showLightboxContent(delay);
            },
            onFailure: function() {
                $('lightboxLoadingScreenMessage').update(lightboxLoadingErrorMessage);
                $('lightboxLoadingScreen').show();
            }
        });
    } // ...or use element 
    if( (typeof(lightboxContentElement) !== 'undefined' && lightboxContentElement != null) ) {
        $('lightboxContents').appendChild($(lightboxContentElement));
        $(lightboxContentElement).show();
        showLightboxContent(0);
    }
}

function showLightboxContent(delay) {
    new Effect.Parallel([
        new Effect.Fade('lightboxLoadingScreen', {sync: true}),
        new Effect.Appear('lightboxContents', {sync: true})
    ], {
        duration: 1,
        delay: delay
    });
    setTimeout(fixScrollContainer, 1000);
}

/**
 * Fixes problem when using scrollContainer and headline of dialog is multiline (see simplePageTemplate.jsp) 
 */
function fixScrollContainer() {
    if( getLightboxBodyHeight() > lightboxHeight ) {
        var scrollContainerElement = null;
        $$('div#lightbox div.scrollContainer').each(function(element) { scrollContainerElement = element; });
        if( scrollContainerElement != null ) {
            scrollContainerElement.style.height = (scrollContainerElement.getHeight() - (getLightboxBodyHeight() - lightboxHeight)) + 'px';
            for(i=0; i<5 && (getLightboxBodyHeight() > lightboxHeight); i++) {
                scrollContainerElement.style.height = (scrollContainerElement.getHeight()-20) + 'px';
            }
        }
    }
}

function hideLightbox() {
    new Effect.Parallel([
        new Effect.Puff('lightbox', {sync: true}),
        new Effect.Fade('lightboxHeader', {sync: true}),
        new Effect.Fade('lightboxContents', {sync: true}),
        new Effect.Fade('lightboxOverlay', {sync: true})
    ], {
        duration: 0.5
    });
    setTimeout(afterHideLightbox, 500);
    if( lightboxOnCloseFunction != null ) lightboxOnCloseFunction();
}

function afterHideLightbox() {
    $('lightboxLoadingScreen').hide();
    // If content element was set - hide it and add it to body
    if( (typeof(lightboxContentElement) !== 'undefined' && lightboxContentElement != null) ) {
        $(lightboxContentElement).hide();
        document.body.appendChild($(lightboxContentElement));
    } else {
       // Otherwise - remove loaded content
       $('lightboxContents').innerHTML = "";
    }
}

function resizeLightboxOverlay() {
    if ($('lightboxOverlay').style.display != "none") {
        var screenSize = getScreenSize();
        $('lightboxOverlay').style.width = screenSize.width + "px";
        $('lightboxOverlay').style.height = screenSize.height + "px";
        var lightboxTop = ((screenSize.height / 2) - (Element.getDimensions('lightbox').height / 2));
        if( lightboxTop < 50 ) lightboxTop = 50;
        var lightboxLeft = ((screenSize.width / 2) - (Element.getDimensions('lightbox').width / 2));
        if( lightboxLeft < 50 ) lightboxLeft = 50;
        $('lightbox').style.top = lightboxTop + 'px';
        $('lightbox').style.left = lightboxLeft + 'px';
    }
}

function getScreenSize() {
    var screenWidth = 0;
    var screenHeight = 0;
    if (window.innerHeight) {
        screenWidth = window.innerWidth;
        screenHeight = window.innerHeight;
    } else if (document.documentElement.clientHeight) {
        screenWidth = document.documentElement.clientWidth;
        screenHeight = document.documentElement.clientHeight;
    } else if (document.body.clientHeight) {
        screenWidth = document.body.clientWidth;
        screenHeight = document.body.clientHeight;
    }
    return {
        "width": screenWidth,
        "height": screenHeight
    }
}

function getScrollY() {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

function getLightboxBodyHeight() {
    return $('lightboxBody').getHeight() + $('lightboxHeader').getHeight();
}
