/*
    Disclaimer

    While we make every effort to ensure that this code is fit for its intended
    purpose, we make no guarantees as to its functionality. CoreTrek AS will
    accept no responsibility for the loss of data or any other damage or
    financial loss caused by use of this code.


    Copyright

    This programming code is copyright of CoreTrek AS. Permission to run this
    code is given to approved users of CoreTrek's publishing system CorePublish.

    This source code may not be copied, modified or otherwise repurposed for use
    by a third party without the written permission of CoreTrek AS.

    Contact webmaster@coretrek.com for information.

    ============================================================================
    IMPORTANT! This javascript is dependent on Prototype.
    ============================================================================
    
    SiteComponents Lightbox
  
    Displays a given URL in a modal layer. All anchor tags that is set with
    the css-class "lightbox" will be opened in a lightbox. Just include this
    javascript to enable.
    
    The script is dependant on Prototype.
    
    * Important SiteComponents requirements: *
    
      - Svalbard lightbox style definitions
      - File html/images/lightbox/ff-overlay-img.png
      - File html/history-frame.php
 
    If you want to programmatically open a lightbox, this can be done using
    the lightbox objects show method like this:
    
    lightbox.show('http://coretrek.no/cms/corepublish/webpublisering/');

    The argument contentUrl is the url for the content being displayed
 
*/

var Lightbox = Class.create({
	isOpenedFromFlash: false,

    initialize: function() {
        this.history = new Object();
        
	    var objBody = document.getElementsByTagName('body').item(0);
	    
	    if(Prototype.Browser.IE) {
		    var objHistoryFrame = document.createElement('iframe');
		    objHistoryFrame.setAttribute('id', 'lightbox-history-frame');
		    objHistoryFrame.style.display = 'none';
		    objHistoryFrame.src = "history-frame.php";
		    objHistoryFrame.style.position = 'absolute';
		    objHistoryFrame.style.top = '0';
		    objHistoryFrame.style.left = '0';
		    objHistoryFrame.style.width = '1px';
		    objHistoryFrame.style.height = '1px';
		    objBody.appendChild(objHistoryFrame);
		    this.historyFrame = objHistoryFrame;

        }
	    
	    // Add the lightbox html structure to end of page
	    var objLightbox = document.createElement('div');
	    objLightbox.setAttribute('id', 'lightbox');
	    objLightbox.style.display = 'none';
	    objBody.appendChild(objLightbox);
	    
	    var objOverlay = document.createElement('div');
	    objOverlay.setAttribute('id', 'lightbox-overlay');
	    objOverlay.style.display = 'none';
	    objLightbox.appendChild(objOverlay);
	    
	    var objContainer = document.createElement('div');
	    objContainer.setAttribute('id', 'lightbox-container');
	    objLightbox.appendChild(objContainer);
	    
	    var objCloseButtonContainer = document.createElement('div');
	    objCloseButtonContainer.setAttribute('id', 'lightbox-close-container');
	    objContainer.appendChild(objCloseButtonContainer);
	    
	    var objCloseButton = document.createElement('a');
	    objCloseButton.setAttribute('id', 'lightbox-close');
	    objCloseButton.setAttribute('href', '#');
	    
	    var objCloseButtonSpan = document.createElement('span');
	    objCloseButton.appendChild(objCloseButtonSpan);
	    
	    var objCloseText = document.createTextNode("Close");
	    objCloseButtonSpan.appendChild(objCloseText);
	    objCloseButtonContainer.appendChild(objCloseButton);
	    
	    var objStart = document.createElement('div');
	    objStart.setAttribute('id', 'lightbox-start');
	    objContainer.appendChild(objStart);
	    
	    var objSpinner = document.createElement('div');
	    objSpinner.setAttribute('id', 'lightbox-spinner');
	    objContainer.appendChild(objSpinner);
	    
	    var objContent = document.createElement('div');
	    objContent.setAttribute('id', 'lightbox-content');
	    objContent.style.display = 'none';
	    objContainer.appendChild(objContent);
	    
	    var objEnd = document.createElement('div');
	    objEnd.setAttribute('id', 'lightbox-end');
	    objContainer.appendChild(objEnd);
	    
		objLightbox.appendChild(objContainer);

		    // lb_scroll_fix START
		    /*
		if(this.isIE6()) {
		    this.resizeOverlayToViewport();
			document.observe('resize', function() {
	           this.resizeOverlayToViewport();
	        });
        }
		    */
		    // lb_scroll_fix STOP
        
		$('lightbox-close').observe('click', function(event) {
            event.stop();
            lightbox.hide();
        });
        
        $('lightbox-overlay').observe('click', function(event) {
            event.stop();
            lightbox.hide();
        });
        
		// Set opacity on overlay layer. Because of a bug in Firefox, causing
		// fixed positioned layers (behind a flash) to render the flash
		// invisible. This has to be done with a semitransparent png on this
		// browser. Make sure that the png has the same design as the css
		// styled overlay layer has on the other browsers.
        if(Prototype.Browser.Gecko) {
            $('lightbox-overlay').setStyle({
                background: 'url(/images/lightbox/ff-overlay-img-black.png)'
            });
        } else {
        	$('lightbox-overlay').style.backgroundColor = "#000000";
            $('lightbox-overlay').setStyle({
                opacity: 0.7
            });
        }
	},
	
	resizeOverlayToViewport: function() {
	    // lb_scroll_fix START
	    /* 
        $('lightbox-overlay').setStyle({
            height: document.viewport.getHeight()+'px'
        });
	    */
	    // lb_scroll_fix STOP
    },

    // Function to be used when opening a lightbox link manually, eg. using
    // onClick instead of using class="lightbox".
    show: function(contentUrl) {
        if(Prototype.Browser.IE) {
	        lightbox.historyFrame.src = "/history-frame.php?modal";
	    } else {
	        window.location.hash = "#modal";
	    }
	    lightbox.open(contentUrl);
	    
	    lightbox.historyPolling = new PeriodicalExecuter(function(pe) {
	        var close = false;
	        if(Prototype.Browser.IE) {
	            var frameTitle = lightbox.historyFrame.contentWindow.document.title;
	            if(frameTitle.indexOf("?modal") < 0) {
	                close = true;
	            }
	        } else {
	            var hash = window.location.hash;
	            if(window.location.hash != "#modal") {
	                close = true;
	            }
	        }
	        
	        if(close) {
	            pe.stop();
	            if(lightbox.isVisible()) {
	                lightbox.hide();
	            }
	        }
	    }, 1);

	},

    hide: function() {
    	try {
	        lightbox.historyPolling.stop();
		} catch (exception) { }
        
		// lb_scroll_fix START
		/*
	    // Re-enable window scrollbars for IE6
	    if(this.isIE6()) {
		    window.scrollTo(this.scolloffset[0], this.scolloffset[1]);
		    document.getElementsByTagName('html').item(0).style.overflow = 'auto';
	    }
		*/
		// lb_scroll_fix STOP
	    
	    $('lightbox').hide();
	    $('lightbox-content').hide();
	    $('lightbox-overlay').hide();
	    
	    this.showPersistentObjects(true);
	    
	    $('lightbox-content').update(" ");
	    
	    if(window.location.hash == "#modal") {
            history.back(1);
        }
	},

    isIE6: function() {
        if(Prototype.Browser.IE && navigator.appVersion.match(/MSIE 6\.0/)) {
            return true;
        } else {
            return false;
        }
    },   

    isIE7: function() {
        if(Prototype.Browser.IE && navigator.appVersion.match(/MSIE 7\.0/)) {
            return true;
        } else {
            return false;
        }
    },
    
	// In IE6/IE7 and Opera some items will always show on top of the lightbox.
	// This is a function used to hide these elements.
	showPersistentObjects: function(show) {
	    $$('select', 'embed', 'object').each(function(element) {
	        if(show) {
	            element.style.visibility = 'visible';
	        } else {
	            element.style.visibility = 'hidden';
	        }
	    });
	},
	
	isVisible: function() {
	   return $('lightbox').visible;
	},
	
	// Private function! Must not be called manually.
	open: function(contentUrl) {
	    // adjust overlay height to cover entire body	    

	    /*
	    	when called from flash, the lightbox-overlay height needs to be set differently
	    */
	    if((lightbox.isIE6() || lightbox.isIE7()) && lightbox.isOpenedFromFlash) {
    	    /*
    	    Somehow document.getElementsByTagName('body').item(0).getHeight() just does not work in IE6 and IE7
	    when the lightbox.open function is called from a flash, who is calling lightbox.show
    	    IE8 is not yet tested.
    	    */
		// scroll to top of page
		window.scrollTo(0,0);
	    	$('lightbox-overlay').style.height = document.viewport.getHeight()+ "px";
    
	    } else {	        
	        /* Sane browsers do this instead */	        
	    
	       $('lightbox-overlay').style.height = Math.max(document.viewport.getHeight(),document.getElementsByTagName('body').item(0).getHeight()) + "px";    
	    }
	    lightbox.isOpenedFromFlash = false;
	    	    
	    // position lightbox top within visible area	    
	    
	    $('lightbox-container').style.top = (document.viewport.getScrollOffsets()[1] + 40) + "px";
	    
        if(contentUrl == null) {
            alert("No URL provided");
            return;
        }
        
                
        this.showPersistentObjects(false);
        $('lightbox-spinner').show();
        $('lightbox-overlay').show();
        $('lightbox').show();
        
        
        
	    // lb_scroll_fix START
	    /*
        // Disable scrollbars for main window when displaying lightbox in IE6
        if(Prototype.Browser.IE && navigator.appVersion.match(/MSIE 6\.0/)) {
            this.scolloffset = document.viewport.getScrollOffsets();
            document.getElementsByTagName('html').item(0).style.overflow = 'hidden';
            window.scrollTo(0, 0);
        }
	    */
	    // lb_scroll_fix STOP
                    
        new Ajax.Request(contentUrl, {
            method: 'get',
            
            onSuccess: function(transport) {                
            
                $('lightbox-content').update(transport.responseText);
                $('lightbox-spinner').hide();
                $('lightbox-content').show();
            },
            
            onFailure: function(request) {               
            
                lightbox.hide();
                alert("Could not connect to URL: " +contentUrl);
            }
        });
	},
	
	// Used to add lightbox to all anchor tags marked with lightbox css class.
	// Also initializes the history functions used to close lightbox with
	// back button.
	load: function() {
		$$('a.lightbox').each(function (element) {
	        element.observe('click', function (event) {
	            event.stop();
	            
	            var element = Event.findElement(event, 'a');
	            if(element != document) {
                    lightbox.show(element.getAttribute('href'));
	            }
	        });
	    });    
	}
});
