// fmlightwindow 1.01
// 
// Based on code lightwindow.js v2.0 from: Kevin P Miller | http://www.stickmanlabs.com
// LightWindow is freely distributable under the terms of an MIT-style license.

if (typeof Effect == 'undefined') 
    throw ("lightwindow.js requires including script.aculo.us' effects.js library!");

// This will stop image flickering in IE6 when elements with images are moved
try {
    document.execCommand("BackgroundImageCache", false, true);
} 
catch (e) {
}

var lightwindow = Class.create();
lightwindow.prototype = {
    //
    //	Setup Variables
    //
    element: null,
    contentToFetch: null,
    windowActive: false,
    dataEffects: [],
    dimensions: {
        cruft: null,
        container: null,
        viewport: {
            height: null,
            width: null,
            offsetTop: null,
            offsetLeft: null
        }
    },
    pagePosition: {
        x: 0,
        y: 0
    },
    pageDimensions: {
        width: null,
        height: null
    },
    preloadImage: [],
    preloadedImage: [],
    galleries: [],
    resizeTo: {
        height: null,
        heightPercent: null,
        width: null,
        widthPercent: null,
        fixedTop: null,
        fixedLeft: null
    },
    scrollbarOffset: 18,
    navigationObservers: {
        previous: null,
        next: null
    },
    containerChange: {
        height: 0,
        width: 0
    },
    activeGallery: false,
    galleryLocation: {
        current: 0,
        total: 0
    },
    //
    //	Initialize the lightwindow.
    //
    initialize: function(options){
        this.options = Object.extend({
            resizeSpeed: 8,
            contentOffset: {
                height: 0,
                width: 0
            },
            selectedElement: null,
						contentOffsetMargin: {
							width: 60
						},
            dimensions: {
                image: {
                    height: 150,
                    width: 200
                },
                page: {
                    height: 150,
                    width: 200
                },
                inline: {
                    height: 150,
                    width: 200 
                }
            },
						headerHeight: 31,
						ajaxParams: 'ajaxContext=true',
            classNames: {
                standard: 'lightwindow',
                action: 'lightwindow_action'
            },
            fileTypes: {
                page: ['asp', 'aspx', 'cgi', 'cfm', 'htm', 'html', 'pl', 'php4', 'php3', 'php', 'php5', 'phtml', 'rhtml', 'shtml', 'txt', 'vbs', 'rb', 'jsp', ''],
                image: ['bmp', 'gif', 'jpg', 'png', 'tiff']
            },
            viewportPadding: 10,
            overlay: {
                opacity: 0.7,
                image: assetsPath + 'fmlightwindow/images/bg_lightwindowOverlay.png'
            },
						titlePosition : 'bottom', //top or bottom or other. (other is for titles positioned outside of content area requires #lightwindow_title_bar_title added to skin and to always be visible)
            sifrTitle: {
                active: null,
                selector: '#lightwindow_title_bar_title',
                css: '.sIFR-root { color: #009ddc; }'
            },
            skin: {
                main: '<div id="lightwindow_container" >' +
			                	'<div id="lightwindow_header_cl" >' +
			                		'<div id="lightwindow_header_cr" >' +
			                			'<div id="lightwindow_header_inner" >' +
			                				'&nbsp;' +
			                			'</div>' +
			                		'</div>' +
			                	'</div>' +
			                	'<div id="lightwindow_stage" >' +
			                		'<div id="lightwindow_contents_cl" >' +
			                			'<div id="lightwindow_contents_cr" >' +
			                				'<div id="lightwindow_contents" >' +
			                					'<div id="lightwindow_contents_inner" >' +
			                					'</div>' +
			                				'</div>' +
			                			'</div>' +
			                		'</div>' +
			                		'<a id="lightwindow_title_bar_close_link" >close</a>' +
			                			'<div id="lightwindow_navigation" >' +
			                				'<a href="#" id="lightwindow_previous" >' +
			                					'<span id="lightwindow_previous_title"></span>' +
			                				'</a>' +
			                				'<a href="#" id="lightwindow_next" >' +
			                					'<span id="lightwindow_next_title"></span>' +
			                				'</a>' +
			                			'</div>' +
			                		'</div>' +
			                	'<div id="lightwindow_footer_cl" >' +
			                		'<div id="lightwindow_footer_cr" >' +
			                			'<div id="lightwindow_footer_inner" >' +
			                				'&nbsp;' +
			                			'</div>' +
			                		'</div>' +
												'</div>' +
			                '</div>',
                loading: '<div id="lightwindow_loading" >' +
                '&nbsp;' +
                '</div>',
                gallery: {}
            },
            postProcess: null,
            skinModifier: null,
            formMethod: 'post',
            hideFlash: false,
            showTitleBar: true, //requires lightwindow_title_bar_title
            animationHandler: false,
            navigationHandler: false,
            transitionHandler: false,
            finalAnimationHandler: false,
            formHandler: false
        }, options || {});
        this.duration = ((11 - this.options.resizeSpeed) * 0.15);
        this._setupLinks();
        this._getScroll();
        this._getPageDimensions();
        this._browserDimensions();
        this._addLightWindowMarkup(false);
        this._setupDimensions();
    },
    //
    //	Activate the lightwindow.
    //
    activate: function(e, link){
        // Clear out the window Contents
       
        this.selectedElement = link;
        this._clearWindowContents(true);
        
        // Add back in out loading panel
        this._addLoadingWindowMarkup();
        
        // Setup the element properties
        this._setupWindowElements(link);
				
				if(this.element.rev != null) {
					$('lightwindow').className = this.element.rev;
				} else {
					$('lightwindow').className = '';
				}
				
        // Setup everything
        this._getScroll();
        this._browserDimensions();
        this._setupDimensions();
        this._toggleTroubleElements('hidden', false);
        this._displayLightWindow('block', 'hidden');
        this._setStatus(true);
        this._monitorKeyboard(true);
        this._prepareIE(true);
        this._loadWindow();
    },
    //
    //	Turn off the window
    //
    deactivate: function(){
        // The window is not active
        this.windowActive = false;
        
        // There is no longer a gallery active
        this.activeGallery = false;
        
        // Kill the animation
        this.animating = false;
        
        // Clear our element
        this.element = null;
        
        // hide the window.
        this._displayLightWindow('none', 'visible');

        if($('map') != null) {
          GUnload();
        }
        
        // Clear out the window Contents
        this._clearWindowContents(false);
        
        // Stop all animation
        var queue = Effect.Queues.get('lightwindowAnimation').each(function(e){
            e.cancel();
        });
        
        // Undo the setup
        this._prepareIE(false);
        this._setupDimensions();
        this._toggleTroubleElements('visible', false);
        this._monitorKeyboard(false);
    },
    //
    //  Initialize specific window
    //
    createWindow: function(element, attributes){
        this._processLink($(element));
    },
    //
    //  Open a Window from a hash of attributes
    //
    activateWindow: function(options){
        this.element = Object.extend({
            href: null,
            title: null,
            rel: null,
						rev: null,
            top: null,
            left: null,
            type: null,
            showImages: null,
            height: null,
            width: null,
            loadingAnimation: null,
            iframeEmbed: null,
            form: null
        }, options || {});
        
        // Set the window type
        this.contentToFetch = this.element.href;
        this.windowType = this.element.type ? this.element.type : this._fileType(this.element.href);
        
        // Clear out the window Contents
        this._clearWindowContents(true);
        
        // Add back in out loading panel
        this._addLoadingWindowMarkup();
        
        // Setup everything
        this._getScroll();
        this._browserDimensions();
        this._setupDimensions();
        this._toggleTroubleElements('hidden', false);
        this._displayLightWindow('block', 'hidden');
        this._setStatus(true);
        this._monitorKeyboard(true);
        this._prepareIE(true);
        this._loadWindow();
    },
    //
    //  Fire off our Form handler
    //
    submitForm: function(e){
        if (this.options.formHandler) {
            this.options.formHandler(e);
        }
        else {
            this._defaultFormHandler(e);
        }
    },
		//
    //  Fire off our internalLink handler
    //
    internal: function(e){
        if (this.options.internalHandler) {
            this.options.internalHandler(e);
        }
        else {
            this._defaultInternalHandler(e);
        }
    },
		//
    //  Fire off our internalLink handler
    //
    external: function(e){
        if (this.options.externalHandler) {
            this.options.externalHandler(e);
        }
        else {
            this._defaultExternalHandler(e);
        }
    },
    //
    //	Reload the window with another location
    //
    openWindow: function(element){
		
        var element = $(element);
        
        // The window is active
        this.windowActive = true;
        
        // Clear out the window Contents
        this._clearWindowContents(true);
        
        // Add back in out loading panel
        this._addLoadingWindowMarkup();
        
        // Setup the element properties
        this._setupWindowElements(element);
        
        this._setStatus(true);
        this._handleTransition();
    },
    //
    //  Navigate the window
    //
    navigateWindow: function(direction){
        this._handleNavigation(false);
        if (direction == 'previous') {
            this.openWindow(this.navigationObservers.previous);
        }
        else 
            if (direction == 'next') {
                this.openWindow(this.navigationObservers.next);
            }
    },
    // 
    //  Set Links Up
    //
    _setupLinks: function(){
        var links = $$('.' + this.options.classNames.standard);
        links.each(function(link){
            this._processLink(link);
        }
.bind(this));
    },
    //
    //  Process a Link
    //
    _processLink: function(link){
    
        if (this._fileType(link.getAttribute('href')) == 'image') {
            if (gallery = this._getGalleryInfo(link.rel)) {
                if (!this.galleries[gallery[0]]) {
                    this.galleries[gallery[0]] = new Array();
                }
                if (!this.galleries[gallery[0]][gallery[1]]) {
                    this.galleries[gallery[0]][gallery[1]] = new Array();
                }
                this.galleries[gallery[0]][gallery[1]].push(link);
            }
        }
        
        // Take care of our inline content
        var url = link.getAttribute('href');
        if (url.indexOf('?') > -1) {
            url = url.substring(0, url.indexOf('?'));
        }
        
        var container = url.substring(url.indexOf('#') + 1);
        if ($(container)) {
            $(container).setStyle({
                display: 'none'
            });
        }
        
        Event.observe(link, 'click', this.activate.bindAsEventListener(this, link), false);
        link.onclick = function(){
            return false;
        };
    },
    //
    //	Setup our actions
    //
    _setupActions: function(){
        var links = $$('#lightwindow_container .' + this.options.classNames.action);
        links.each(function(link){
          if(link.tagName == 'SELECT') {
            Event.observe(link, 'onchange', this[link.getAttribute('rel')].bindAsEventListener(this, link), false);
            link.onchange = function(){
                return false;
            };
          } else {
            Event.observe(link, 'click', this[link.getAttribute('rel')].bindAsEventListener(this, link), false);
            link.onclick = function(){
                return false;
            };
         }
        }
.bind(this));
    },
    //
    //	Add the markup to the page.
    //
    _addLightWindowMarkup: function(rebuild){
        var overlay = Element.extend(document.createElement('div'));
        overlay.setAttribute('id', 'lightwindow_overlay');
        // FF Mac has a problem with putting Flash above a layer without a 100% opacity background, so we need to use a pre-made
        if (Prototype.Browser.Gecko) {
            overlay.setStyle({
                backgroundImage: 'url(' + this.options.overlay.image + ')',
                backgroundRepeat: 'repeat',
                height: this.pageDimensions.height + 'px'
            });
        }
        else {
            overlay.setStyle({
                opacity: this.options.overlay.opacity,
                backgroundImage: 'url(' + this.options.overlay.image + ')',
                backgroundRepeat: 'repeat',
                height: this.pageDimensions.height + 'px'
            });
        }
        		
        var lw = new Element('div', {'id': 'lightwindow'}).update(this.options.skin.main);
		
				if (this.options.skinModifier != null) {
            lw = this.options.skinModifier(lw);
        }
		
        var body = document.getElementsByTagName('body')[0];
        body.appendChild(overlay);
        body.appendChild(lw);

        if ($('lightwindow_title_bar_close_link')) {
            Event.observe('lightwindow_title_bar_close_link', 'click', this.deactivate.bindAsEventListener(this));
            $('lightwindow_title_bar_close_link').onclick = function(){
                return false;
            };
        }
				
				try {
					if ($('lightwindow_container') == null) {
							throw ("A div with #lightwindow_container is required.");
					}
					if ($('lightwindow_contents') == null) {
							throw ("A div with #lightwindow_contents is required.");
					}
				} 
				catch (e) {
					alert(e);
				}
        
        Event.observe($('lightwindow_previous'), 'click', this.navigateWindow.bind(this, 'previous'), false);
        $('lightwindow_previous').onclick = function(){
            return false;
        };
        Event.observe($('lightwindow_next'), 'click', this.navigateWindow.bind(this, 'next'), false);
        $('lightwindow_next').onclick = function(){
            return false;
        };
        
        // Because we use position absolute, kill the scroll Wheel on animations
        if (Prototype.Browser.IE) {
            Event.observe(document, 'mousewheel', this._stopScrolling.bindAsEventListener(this), false);
        }
        else {
            Event.observe(window, 'DOMMouseScroll', this._stopScrolling.bindAsEventListener(this), false);
        }
        
        Event.observe(overlay, 'click', this.deactivate.bindAsEventListener(this), false);
        overlay.onclick = function(){
            return false;
        };
        
        $('lightwindow_overlay').insert({top: new Element('span', {id: 'lightwindow_overlay_close'}).update('x')});
    },
    //
    //  Add loading window markup
    //
    _addLoadingWindowMarkup: function(){
        $('lightwindow_contents').insert({bottom: this.options.skin.loading});
    },
    //
    //  Setup the window elements
    //
    _setupWindowElements: function(link){
        this.element = link;
        this.element.title = null ? '' : link.getAttribute('title');
        this.element.rel = null ? '' : link.getAttribute('rel');
        this.element.rev = null ? '' : link.getAttribute('rev');
				
        // Set the window type
        this.contentToFetch = this.element.href;
        this.windowType = this._fileType(this.contentToFetch);
    },
    //
    //  Clear the window contents out
    //
    _clearWindowContents: function(contents){
        // If there is an iframe, its got to go
        if ($('lightwindow_iframe')) {
            Element.remove($('lightwindow_iframe'));
        }
        
        // Stop playing an object if its still around
        if ($('lightwindow_media_primary')) {
            try {
                $('lightwindow_media_primary').Stop();
            } 
            catch (e) {
            }
            Element.remove($('lightwindow_media_primary'));
        }
        
        // Stop playing an object if its still around		
        if ($('lightwindow_media_secondary')) {
            try {
                $('lightwindow_media_secondary').Stop();
            } 
            catch (e) {
            }
            Element.remove($('lightwindow_media_secondary'));
        }
        
        this.activeGallery = false;
        this._handleNavigation(this.activeGallery);
        
        if (contents) {
            // Empty the contents
            $('lightwindow_contents').update('<div id=\"lightwindow_contents_inner\"><\/div>');
						
            // Reset the scroll bars
            $('lightwindow_contents').setStyle({
                overflow: 'hidden'
            });
            
            if (!this.windowActive) {
                if ($('lightwindow_title_bar_title')) {
                    $('lightwindow_title_bar_title').update('');
                }
            }
        }
        
        this.resizeTo.height = null;
        this.resizeTo.width = null;
    },
    //
    //	Set the status of our animation to keep things from getting clunky
    //
    _setStatus: function(status){
        this.animating = status;
        if (status) {
            Element.show('lightwindow_loading');
        }
        if (!(/MSIE 6./i.test(navigator.userAgent))) {
            this._fixedWindow(status);
        }
    },
    //
    //  Make this window Fixed
    //
    _fixedWindow: function(status){
        if (status) {
            if (this.windowActive) {
                this._getScroll();
                $('lightwindow').setStyle({
                    position: 'absolute',
                    top: parseFloat($('lightwindow').getStyle('top')) + this.pagePosition.y + 'px',
                    left: parseFloat($('lightwindow').getStyle('left')) + this.pagePosition.x + 'px'
                });
            }
            else {
                $('lightwindow').setStyle({
                    position: 'absolute'
                });
            }
        }
        else {
            if (this.windowActive) {
                this._getScroll();
                $('lightwindow').setStyle({
                    position: 'fixed',
                    top: parseFloat($('lightwindow').getStyle('top')) - this.pagePosition.y + 'px',
                    left: parseFloat($('lightwindow').getStyle('left')) - this.pagePosition.x + 'px'
                });
            }
            else {
                if ($('lightwindow_iframe')) {
                    // Ideally here we would set a 50% value for top and left, but Safari rears it ugly head again and we need to do it by pixels
                    this._browserDimensions();
                }
                $('lightwindow').setStyle({
                    position: 'fixed',
                    top: this.dimensions.viewport.height / 2 + 'px',
                    left: this.dimensions.viewport.width / 2 + 'px'
                });
            }
        }
    },
    //
    //	Prepare the window for IE.
    //
    _prepareIE: function(setup){
        if (Prototype.Browser.IE) {
            var height, overflowX, overflowY;
            if (setup) {
                var height = '100%';
            }
            else {
                var height = 'auto';
            }
            var body = document.getElementsByTagName('body')[0];
            var html = document.getElementsByTagName('html')[0];
            html.style.height = body.style.height = height;
        }
    },
    _stopScrolling: function(e){
        if (this.animating) {
            if (e.preventDefault) {
                e.preventDefault();
            }
            e.returnValue = false;
        }
    },
    //
    //	Get the scroll for the page.
    //
    _getScroll: function(){
        if (typeof(window.pageYOffset) == 'number') {
            this.pagePosition.x = window.pageXOffset;
            this.pagePosition.y = window.pageYOffset;
        }
        else 
            if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
                this.pagePosition.x = document.body.scrollLeft;
                this.pagePosition.y = document.body.scrollTop;
            }
            else 
                if (document.documentElement) {
                    this.pagePosition.x = document.documentElement.scrollLeft;
                    this.pagePosition.y = document.documentElement.scrollTop;
                }
    },
    //
    //	Reset the scroll.
    //
    _setScroll: function(x, y){
        document.documentElement.scrollLeft = x;
        document.documentElement.scrollTop = y;
    },
    //
    //	Hide Selects from the page because of IE.
    //     We could use iframe shims instead here but why add all the extra markup for one browser when this is much easier and cleaner
    //
    _toggleTroubleElements: function(visibility, content){
   if ((/MSIE 6./i.test(navigator.userAgent))) {
   	var BG_IMG_PATH = /url\(([^\)]*)\)/;
   	
   	$('lightwindow').select('*').each(function(elm){
   		var imgStyle = elm.getStyle('background-image');
   		
   		if (imgStyle.toLowerCase().indexOf(".png") != -1) {
   		
   			var bgImg = imgStyle.replace(BG_IMG_PATH, "$1");
   			
   			// get unquoted image path
						if (bgImg.indexOf("\"") != -1) {
							bgImg = bgImg.substr(1, bgImg.length - 2);
						}
						
						var repeatStyle = elm.getStyle('background-repeat');
						var bgSizing = (repeatStyle == "no-repeat") ? "crop" : "scale";
						
						// insert MS filter code
						elm.style.background = "none";
						elm.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"" + bgImg + "\", sizingMethod=\"" + bgSizing + "\");";
					
					
					}
				});
			}
		
        if (content) {
            var selects = $('lightwindow_contents').getElementsByTagName('select');
        }
        else {
            var selects = document.getElementsByTagName('select');
        }
        if ((/MSIE 6./i.test(navigator.userAgent))) {
					
					
					
					
				 for (var i = 0; i < selects.length; i++) {
				 	selects[i].style.visibility = visibility; 
				 }
				 
				}
        if (!content) {
            if (this.options.hideFlash) {
                var objects = document.getElementsByTagName('object');
                for (i = 0; i != objects.length; i++) {
                    objects[i].style.visibility = visibility;
                }
                var embeds = document.getElementsByTagName('embed');
                for (i = 0; i != embeds.length; i++) {
                    embeds[i].style.visibility = visibility;
                }
            }
            var iframes = document.getElementsByTagName('iframe');
            for (i = 0; i != iframes.length; i++) {
                iframes[i].style.visibility = visibility;
            }
        }
    },
    // 
    //  Get the actual page size
    //
    _getPageDimensions: function(){
        var xScroll, yScroll;
        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        }
        else 
            if (document.body.scrollHeight > document.body.offsetHeight) {
                xScroll = document.body.scrollWidth;
                yScroll = document.body.scrollHeight;
            }
            else {
                xScroll = document.body.offsetWidth;
                yScroll = document.body.offsetHeight;
            }
        
        var windowWidth, windowHeight;
        if (self.innerHeight) {
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        }
        else 
            if (document.documentElement && document.documentElement.clientHeight) {
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
            }
            else 
                if (document.body) {
                    windowWidth = document.body.clientWidth;
                    windowHeight = document.body.clientHeight;
                }
        
        if (yScroll < windowHeight) {
            this.pageDimensions.height = windowHeight;
        }
        else {
            this.pageDimensions.height = yScroll;
        }
        
        if (xScroll < windowWidth) {
            this.pageDimensions.width = windowWidth;
        }
        else {
            this.pageDimensions.width = xScroll;
        }
    },
    //
    //	Display the lightWindow.
    //
    _displayLightWindow: function(display, visibility){
        $('lightwindow_overlay').style.display = $('lightwindow').style.display = $('lightwindow_container').style.display = display;
        $('lightwindow_overlay').style.visibility = $('lightwindow').style.visibility = $('lightwindow_container').style.visibility = visibility;
    },
    //
    //	Setup Dimensions of lightwindow.
    
    //
    _setupDimensions: function(){
    
        var originalHeight, originalWidth;
        switch (this.windowType) {
            case 'page':
                originalHeight = this.options.dimensions.page.height;
                originalWidth = this.options.dimensions.page.width;
                break;
                
            case 'image':
                originalHeight = this.options.dimensions.image.height;
							  originalWidth = this.options.dimensions.image.width;
                break;
                
            case 'inline':
                originalHeight = this.options.dimensions.inline.height;
                originalWidth = this.options.dimensions.inline.width;
                break;
                
            default:
                originalHeight = this.options.dimensions.page.height;
                originalWidth = this.options.dimensions.page.width;
                break;
                
        }
        
        var offsetHeight = this.dimensions.viewport.height / 2 + this.pagePosition.y;
        var offsetWidth = this.dimensions.viewport.width / 2 + this.pagePosition.x;
        
        // So if a theme has say shadowed edges, they should be consistant and take care of in the contentOffset
        $('lightwindow').setStyle({
            top: offsetHeight + 'px',
            left: offsetWidth + 'px'
        });
        
        
        $('lightwindow_container').setStyle({
            height: originalHeight + 'px',
            width: (originalWidth + this.options.contentOffsetMargin.width) + 'px',
            left: -((originalWidth + this.options.contentOffsetMargin.width) / 2) + 'px',
            top: -(originalHeight / 2) + 'px'
        });
        
        $('lightwindow_contents').setStyle({
            height: originalHeight + 'px',
            width: originalWidth + 'px'
        });
    },
    //
    //	Get the type of file.
    //
    _fileType: function(url){
        var image = new RegExp("[^\.]\.(" + this.options.fileTypes.image.join('|') + ")\s*$", "i");
        if (image.test(url)) 
            return 'image';
        if (url.indexOf('#') > -1 && (document.domain == this._getDomain(url))) 
            return 'inline';
        if (url.indexOf('?') > -1) 
            url = url.substring(0, url.indexOf('?'));
        var type = 'unknown';
        var page = new RegExp("[^\.]\.(" + this.options.fileTypes.page.join('|') + ")\s*$", "i");
        if (page.test(url) || url.substr((url.length - 1), url.length) == '/') 
            type = 'page';
        return type;
    },
    //
    //  Get file Extension
    //
    _fileExtension: function(url){
        if (url.indexOf('?') > -1) {
            url = url.substring(0, url.indexOf('?'));
        }
        var extenstion = '';
        for (var x = (url.length - 1); x > -1; x--) {
            if (url.charAt(x) == '.') {
                return extenstion;
            }
            extenstion = url.charAt(x) + extenstion;
        }
    },
    //
    //	Monitor the keyboard while this lightwindow is up
    //
    _monitorKeyboard: function(status){
        if (status) 
            document.onkeydown = this._eventKeypress.bind(this);
        else 
            document.onkeydown = '';
    },
    //
    //  Perform keyboard actions
    //
    _eventKeypress: function(e){
        if (e == null) {
            var keycode = event.keyCode;
        }
        else {
            var keycode = e.which;
        }
        
        switch (keycode) {
            case 27:
                this.deactivate();
                break;
                
            case 13:
                return;default:
                break;
        }
        
        // Gotta stop those quick fingers
        if (this.animating) {
            return false;
        }
        
        switch (String.fromCharCode(keycode).toLowerCase()) {
            case 'p':
                if (this.navigationObservers.previous) {
                    this.navigateWindow('previous');
                }
                break;
                
            case 'n':
                if (this.navigationObservers.next) {
                    this.navigateWindow('next');
                }
                break;
                
            default:
                break;
        }
    },
    //
    //	Get Gallery Information
    //
    _getGalleryInfo: function(rel){
        if (!rel) 
            return false;
        if (rel.indexOf('[') > -1) {
            return new Array(escape(rel.substring(0, rel.indexOf('['))), escape(rel.substring(rel.indexOf('[') + 1, rel.indexOf(']'))));
        }
        else {
            return false;
        }
    },
    //
    //	Get the domain from a string.
    //
    _getDomain: function(url){
        var leadSlashes = url.indexOf('//');
        var domainStart = leadSlashes + 2;
        var withoutResource = url.substring(domainStart, url.length);
        var nextSlash = withoutResource.indexOf('/');
        var domain = withoutResource.substring(0, nextSlash);
        if (domain.indexOf(':') > -1) {
            var portColon = domain.indexOf(':');
            domain = domain.substring(0, portColon);
        }
        return domain;
    },
    //
    //  Get the Browser Viewport Dimensions
    //
    _browserDimensions: function(){
        if (Prototype.Browser.IE) {
            this.dimensions.viewport.height = document.documentElement.clientHeight;
            this.dimensions.viewport.width = document.documentElement.clientWidth;
        }
        else {
            this.dimensions.viewport.height = window.innerHeight;
            this.dimensions.viewport.width = document.width || document.body.offsetWidth;
        }
    },
    //
    //  Get the scrollbar offset, I don't like this method but there is really no other way I can find.
    //
    _getScrollerWidth: function(){
        var scrollDiv = Element.extend(document.createElement('div'));
        scrollDiv.setAttribute('id', 'lightwindow_scroll_div');
        scrollDiv.setStyle({
            position: 'absolute',
            top: '-10000px',
            left: '-10000px',
            width: '100px',
            height: '100px',
            overflow: 'hidden'
        });
        
        var contentDiv = Element.extend(document.createElement('div'));
        contentDiv.setAttribute('id', 'lightwindow_content_scroll_div');
        contentDiv.setStyle({
            width: '100%',
            height: '200px'
        });
        
        scrollDiv.appendChild(contentDiv);
        
        var body = document.getElementsByTagName('body')[0];
        body.appendChild(scrollDiv);
        
        var noScroll = $('lightwindow_content_scroll_div').offsetWidth;
        scrollDiv.style.overflow = 'auto';
        var withScroll = $('lightwindow_content_scroll_div').offsetWidth;
        
        Element.remove($('lightwindow_scroll_div'));
        
        this.scrollbarOffset = noScroll - withScroll;
    },
    //
    //  Get the outer HTML of an object CROSS BROWSER
    //
    _outerHTML: function(object){
        if (Prototype.Browser.IE) {
            return object.outerHTML;
        }
        else {
            var clone = object.cloneNode(true);
            var cloneDiv = document.createElement('div');
            cloneDiv.appendChild(clone);
            return cloneDiv.innerHTML;
        }
    },
    //
    //  Convert an object to markup
    //
    _convertToMarkup: function(object, closeTag){
        var markup = this._outerHTML(object).replace('</' + closeTag + '>', '');
        if (Prototype.Browser.IE) {
            for (var i = 0; i < object.childNodes.length; i++) {
                markup += this._outerHTML(object.childNodes[i]);
            }
            markup += '</' + closeTag + '>';
        }
        return markup;
    },
    //
    //  Load the window Information
    //  
    _loadWindow: function(){
        switch (this.windowType) {
            case 'image':
                
                var current = 0;
                var images = [];
                this.checkImage = [];
                this.resizeTo.height = this.resizeTo.width = 0;
                this.imageCount = 1;
                
                // If there is a gallery get it
                if (gallery = this._getGalleryInfo(this.element.rel)) {
                    for (current = 0; current < this.galleries[gallery[0]][gallery[1]].length; current++) {
                        if (this.contentToFetch.indexOf(this.galleries[gallery[0]][gallery[1]][current].href) > -1) {
                            break;
                        }
                    }
                    
                    if (this.galleries[gallery[0]][gallery[1]][current - this.imageCount]) {
                        this.navigationObservers.previous = this.galleries[gallery[0]][gallery[1]][current - this.imageCount];
                    }
                    else {
                        this.navigationObservers.previous = false;
                    }
                    
                    if (this.galleries[gallery[0]][gallery[1]][current + this.imageCount]) {
                        this.navigationObservers.next = this.galleries[gallery[0]][gallery[1]][current + this.imageCount];
                    }
                    else {
                        this.navigationObservers.next = false;
                    }
                    
                    this.activeGallery = true;
                }
                else {
                    this.navigationObservers.previous = false;
                    this.navigationObservers.next = false;
                    
                    this.activeGallery = false;
                }
                
                for (var i = current; i < (current + this.imageCount); i++) {
                
                    if (gallery && this.galleries[gallery[0]][gallery[1]][i]) {
                        this.contentToFetch = this.galleries[gallery[0]][gallery[1]][i].href;
                        
                        this.galleryLocation = {
                            current: (i + 1) / this.imageCount,
                            total: (this.galleries[gallery[0]][gallery[1]].length) / this.imageCount
                        };
                        
                        if (!this.galleries[gallery[0]][gallery[1]][i + this.imageCount]) {
                            $('lightwindow_next').setStyle({
                                display: 'none'
                            });
                        }
                        else {
                            $('lightwindow_next').setStyle({
                                display: 'block'
                            });
                            $('lightwindow_next_title').update(this.galleries[gallery[0]][gallery[1]][i + this.imageCount].title);
                        }
                        
                        if (!this.galleries[gallery[0]][gallery[1]][i - this.imageCount]) {
                            $('lightwindow_previous').setStyle({
                                display: 'none'
                            });
                        }
                        else {
                            $('lightwindow_previous').setStyle({
                                display: 'block'
                            });
                            $('lightwindow_previous_title').update(this.galleries[gallery[0]][gallery[1]][i - this.imageCount].title);
                        }
                    }
                    
                        $('lightwindow_contents_inner').insert({
                            top: new Element('img', {
                                src: this.contentToFetch,
                                id: 'lightwindow_image_' + i
                            })
                        });
                    
                    // We have to do this instead of .onload 
                    this.checkImage[i] = new PeriodicalExecuter(function(i){
                        if (!(typeof $('lightwindow_image_' + i).naturalWidth != "undefined" && $('lightwindow_image_' + i).naturalWidth == 0)) {
                        
                            this.checkImage[i].stop();
                            
                            var imageHeight = $('lightwindow_image_' + i).getHeight();
                            if (imageHeight > this.resizeTo.height) {
                                this.resizeTo.height = imageHeight;
                            }
                            this.resizeTo.width += $('lightwindow_image_' + i).getWidth();
                            
                            this.imageCount--;
                             
                            if (this.imageCount == 0) {
                                this._processWindow();
                            }
                        }
                        
                    }
.bind(this, i), 1);
                }
                
                break;
                
            case 'page':
                
								
                var newAJAX = new Ajax.Request(this.contentToFetch, {
                    method: 'get',
                    parameters: this.options.ajaxParams,
                    onComplete: function(response){
																					
		                    $('lightwindow_contents_inner').insert({top: response.responseText});

                        

                        if (this.options.postProcess != null && $('map') != null) {
                            params = this.selectedElement.href.toQueryParams();
                            link = params['address'].gsub('+', ' ');
                            this.options.postProcess(link);
                        }

                        

                        this.resizeTo.height = $('lightwindow_contents').scrollHeight;
                        this.resizeTo.width = $('lightwindow_contents').scrollWidth;
                        this._processWindow();
                    }
.bind(this)
	
                });
                break;
                
            case 'inline':
                
                var content = this.contentToFetch;
                if (content.indexOf('?') > -1) {
                    content = content.substring(0, content.indexOf('?'));
                }
                content = content.substring(content.indexOf('#') + 1);
                
							  $('lightwindow_contents_inner').insert({top: $(content).innerHTML});
								
                this.resizeTo.height = $('lightwindow_contents').scrollHeight + (this.options.contentOffset.height);
                this.resizeTo.width = $('lightwindow_contents').scrollWidth + (this.options.contentOffset.width);
                
                this._toggleTroubleElements('hidden', true); 
                this._processWindow();
                
                break;
                
            default:
                throw ("Page Type could not be determined, please amend this lightwindow URL " + this.contentToFetch);
                break;
        }
    },
    //
    //  Resize the Window to fit the viewport if necessary
    //
    _resizeWindowToFit: function(){
    
        if (this.resizeTo.height + this.dimensions.cruft.height > this.dimensions.viewport.height) {
            var heightRatio = this.resizeTo.height / this.resizeTo.width;
            this.resizeTo.height = this.dimensions.viewport.height - this.dimensions.cruft.height - (2 * this.options.viewportPadding);
            // We only care about ratio's with this window type			
            if (this.windowType == 'image') {
                this.resizeTo.width = this.resizeTo.height / heightRatio;
            }
        }
        if (this.resizeTo.width + this.dimensions.cruft.width > this.dimensions.viewport.width) {
            var widthRatio = this.resizeTo.width / this.resizeTo.height;
            this.resizeTo.width = this.dimensions.viewport.width - 2 * this.dimensions.cruft.width - (2 * this.options.viewportPadding);
            // We only care about ratio's with this window type
            if (this.windowType == 'image') {
                this.resizeTo.height = this.resizeTo.width / widthRatio;
                
            }
        }
        
    },
    //
    //  Process the Window
    //
    _processWindow: function(){
        // Clean out our effects
        this.dimensions.dataEffects = [];
					
            if (this.element.title != null && this.element.title != 'null' && this.element.title != '') {
          
							 if ( this.options.titlePosition == 'top') {
                        $('lightwindow_contents_inner').insert({
                            top: new Element('span', {id: 'lightwindow_title_bar_title'}).update(this.element.title)
                        });
                    } else if ( this.options.titlePosition == 'other' ){
											$('lightwindow_title_bar_title').update(this.element.title);
										} else {
												$('lightwindow_contents_inner').insert({
                            bottom: new Element('span', {id: 'lightwindow_title_bar_title'
                            }).update(this.element.title)
                        });
									  }

                if (this.options.sifrTitle.active != null) {
									$('lightwindow_title_bar_title').removeClassName('sIFR-replaced');
                   sIFR.replace(this.options.sifrTitle.active, {
                        selector: this.options.sifrTitle.selector,
                        css: this.options.sifrTitle.css,
                        transparent: true,
                        forceSingleLine: true
                    });
                }
            }

          if (this.options.postProcess != null) {
             this.options.postProcess();
          }

        var originalContainerDimensions = {
            height: $('lightwindow_container').getHeight(),
            width: $('lightwindow_container').getWidth()
        };
        
        // Position the window
        $('lightwindow_container').setStyle({
            height: 'auto',
            // We need to set the width to a px not auto as opera has problems with it
            width: $('lightwindow_container').getWidth() + this.options.contentOffset.width - (this.windowActive ? this.options.contentOffset.width : 0) + 'px'
        });
        
        var newContainerDimensions = {
            height: $('lightwindow_container').getHeight(),
            width: $('lightwindow_container').getWidth()
        };
        
        // We need to record the container dimension changes
        this.containerChange = {
            height: originalContainerDimensions.height - newContainerDimensions.height,
            width: originalContainerDimensions.width - newContainerDimensions.width
        };
        
        // Get out general dimensions
        this.dimensions.container = {
            height: $('lightwindow_container').getHeight(),
            width: $('lightwindow_container').getWidth()
        };
        this.dimensions.cruft = {
            height: this.dimensions.container.height - $('lightwindow_contents').getHeight() + this.options.contentOffset.height,
            width: this.dimensions.container.width - $('lightwindow_contents').getWidth() + this.options.contentOffset.width
        };
        
        
        // Set Sizes if we need too
        this._resizeWindowToFit(); // Even if the window is preset we still don't want it to go outside of the viewport
        if (!this.windowActive) {
            // Position the window
            $('lightwindow_container').setStyle({
                left: -(this.dimensions.container.width / 2) + 'px',
                top: -(this.dimensions.container.height / 2) + 'px'
            });
        }
        
        $('lightwindow_container').setStyle({
            height: this.dimensions.container.height + 'px',
            width: this.dimensions.container.width + 'px'
        });
        
        // We are ready, lets show this puppy off!
        this._displayLightWindow('block', 'visible');
        this._animateLightWindow();
        
    },
    //
    //  Fire off our animation handler
    //
    _animateLightWindow: function(){
        if (this.options.animationHandler) {
            this.options.animationHandler().bind(this);
        }
        else {
            this._defaultAnimationHandler();
        }
    },
    //
    //  Fire off our transition handler
    //
    _handleNavigation: function(display){
        if (this.options.navigationHandler) {
            this.options.navigationHandler().bind(this, display);
        }
        else {
            this._defaultDisplayNavigation(display);
        }
    },
    //
    //  Fire off our transition handler
    //
    _handleTransition: function(){
        if (this.options.transitionHandler) {
            this.options.transitionHandler().bind(this);
        }
        else {
            this._defaultTransitionHandler();
        }
    },
    //
    //  Handle the finish of the window animation
    // 
    _handleFinalWindowAnimation: function(delay){
        if (this.options.finalAnimationHandler) {
            this.options.finalAnimationHandler().bind(this, delay);
        }
        else {
            this._defaultfinalWindowAnimationHandler(delay);
        }
    },
    //
    //  Display the navigation 
    //
    _defaultDisplayNavigation: function(display){
        if (display) {
					
						var titleHeight = $('lightwindow_contents').getHeight();
						var marginTop = this.options.headerHeight;
        		if($('lightwindow_title_bar_title') && this.options.titlePosition == 'bottom' ) { 
							titleHeight = titleHeight - $('lightwindow_title_bar_title').getHeight();
						}
						if($('lightwindow_title_bar_title') && this.options.titlePosition == 'top' ) { 
							marginTop = marginTop + $('lightwindow_title_bar_title').getHeight();
							titleHeight = titleHeight - $('lightwindow_title_bar_title').getHeight();
						}
						
            $('lightwindow_navigation').setStyle({
                display: 'block',
                height: titleHeight + 'px',
                width: '100%',
                marginTop: marginTop + 'px'
            });
        }
        else {
            $('lightwindow_navigation').setStyle({
                display: 'none',
                height: 'auto',
                width: 'auto'
            });
        }
    },
    //
    //  This is the default animation handler for LightWindow
    //
    _defaultAnimationHandler: function(){
    
        var resized = false;
        var ratio = this.dimensions.container.width - $('lightwindow_contents').getWidth() + this.resizeTo.width + this.options.contentOffset.width;
        if (ratio != $('lightwindow_container').getWidth()) {
        
            new Effect.Parallel([new Effect.Scale('lightwindow_contents', 100 * (this.resizeTo.width / $('lightwindow_contents').getWidth()), {
                scaleFrom: 100 * ($('lightwindow_contents').getWidth() / ($('lightwindow_contents').getWidth() + (this.options.contentOffset.width))),
                sync: true,
                scaleY: false,
                scaleContent: false
            }), new Effect.Scale('lightwindow_container', 100 * (ratio / (this.dimensions.container.width)), {
                sync: true,
                scaleY: false,
                scaleFromCenter: true,
                scaleContent: false
            })], {
                duration: this.duration,
                delay: 0.1,
                queue: {
                    position: 'end',
                    scope: 'lightwindowAnimation'
                }
            });
        }
        
        ratio = this.dimensions.container.height - $('lightwindow_contents').getHeight() + this.resizeTo.height + this.options.contentOffset.height;
        
        var titleHeight = 0;
				if(this.options.titlePosition != 'other' ) {
	        if ($('lightwindow_title_bar_title')) {
	            titleHeight = $('lightwindow_title_bar_title').getHeight();
	        }
				}
        
        if (ratio != $('lightwindow_container').getHeight() + titleHeight) {
        
            new Effect.Parallel([new Effect.Scale('lightwindow_contents', 100 * (((this.resizeTo.height + titleHeight) * 1) / $('lightwindow_contents').getHeight()), {
                scaleFrom: 100 * ($('lightwindow_contents').getHeight() / ($('lightwindow_contents').getHeight() + (this.options.contentOffset.height))),
                sync: true,
                scaleX: false,
                scaleContent: false
            }), new Effect.Scale('lightwindow_container', 100 * (ratio / (this.dimensions.container.height)), {
                sync: true,
                scaleX: false,
                scaleFromCenter: true,
                scaleContent: false
            })], {
                duration: this.duration,
                afterFinish: function(){
                    if (this.dimensions.dataEffects.length >= 0) { //fm edit other wise animation doesnt work without
                        new Effect.Parallel(this.dimensions.dataEffects, {
                            duration: this.duration,
                            afterFinish: function(){
                                this._finishWindow();
                            }
.bind(this)                            ,
                            queue: {
                                position: 'end',
                                scope: 'lightwindowAnimation'
                            }
                        });
                    }
                }
.bind(this)                ,
                queue: {
                    position: 'end',
                    scope: 'lightwindowAnimation'
                }
            });
            resized = true;
        }
        // We need to do our data effect since there was no resizing
        if (!resized) {
        
            new Effect.Parallel(this.dimensions.dataEffects, {
                duration: this.duration,
                beforeStart: function(){
                    if (this.containerChange.height != 0 || this.containerChange.width != 0) {
                        new Effect.MoveBy('lightwindow_container', this.containerChange.height, this.containerChange.width, {
                            transition: Effect.Transitions.sinoidal
                        });
                    }
                }
.bind(this)                ,
                afterFinish: function(){
                    this._finishWindow();
                }
.bind(this)                ,
                queue: {
                    position: 'end',
                    scope: 'lightwindowAnimation'
                }
            });
        }
        
    },
    //
    //  Finish up Window Animation
    //
    _defaultfinalWindowAnimationHandler: function(delay){
    
        Effect.Fade('lightwindow_loading', {
            duration: 0.6,
            delay: 0.1,
            afterFinish: function(){
                // Just in case we need some scroll goodness (this also avoids the swiss cheese effect)
                if (this.windowType != 'image') {
                    $('lightwindow_contents').setStyle({
                        overflowY: 'auto' //proabbly should set this to auto if height of light box is less than window
                    });
                }
                this._handleNavigation(this.activeGallery);
                this._setStatus(false);
            }
.bind(this)            ,
            queue: {
                position: 'end',
                scope: 'lightwindowAnimation'
            }
        });
    },
    //
    //  Default Transition Handler
    //
    _defaultTransitionHandler: function(){
    
        // Clean out our effects
        this.dimensions.dataEffects = [];
        
        // We always want the title bar as well
        if ($('lightwindow_title_bar_inner')) {
            this.dimensions.dataEffects.push(new Effect.Morph('lightwindow_title_bar_inner', {
                sync: true,
                style: {
                    height: '0px',
                    marginTop: this.options.headerHeight + 'px'
                }
            }), new Effect.Fade('lightwindow_title_bar_inner', {
                sync: true,
                from: 1.0,
                to: 0.0
            }));
        }
        new Effect.Parallel(this.dimensions.dataEffects, {
            duration: this.duration,
            afterFinish: function(){
                this._loadWindow();
            }
.bind(this)            ,
            queue: {
                position: 'end',
                scope: 'lightwindowAnimation'
            }
        });
    },
    //
    //	Default Form handler for LightWindow
    //
    _defaultFormHandler: function(e){

     var formElement = $('lightwindow').select('form')[0];
	   //var formElement = Event.element(e).form; //not working ie7/6 see above hack works for only one form
		 var formParams = formElement.serialize();
		
		 if (this.options.ajaxParams != '' && this.options.ajaxParams != null) {
	 			formParams += '&' + this.options.ajaxParams;
	 	 }
		 
		 var element = new Element('a', {href: Event.element(e).form.action});

     if (this.options.formMethod != null) {
			var newAJAX = new Ajax.Request(formElement.action, {
				method: this.options.formMethod,
				parameters: formParams,
				onComplete: function(response){

        // alert('hi' + response.transport.toSource());

					this.windowActive = true;
        	
	        // Clear out the window Contents
	        this._clearWindowContents(true);
	        
	        // Add back in out loading panel
	        this._addLoadingWindowMarkup();
				
					$('lightwindow_contents_inner').insert({
						top: response.responseText
					});

     

					this._setStatus(true);
					$('lightwindow_contents_inner').setStyle('overflow: hidden');
					this.resizeTo.height = $('lightwindow_contents_inner').scrollHeight;
					this.resizeTo.width = $('lightwindow_contents_inner').scrollWidth;
					$('lightwindow_contents_inner').setStyle('overflow: inherit');
					this._processWindow();
				}
.bind(this)
			});
		}
    },
		//
    //	Default internal link handler for LightWindow
    //
		_defaultInternalHandler: function(e){
		
    var element  = Event.element(e).up('a');
    if(element == undefined) {
      element = Event.element(e);
    }
    
		var newAJAX = new Ajax.Request(element.href, {
				method: 'get',
				parameters: this.options.ajaxParams,
				onComplete: function(response){
					
					this.windowActive = true;
        	
	        // Clear out the window Contents
	        this._clearWindowContents(true);
	        
	        // Add back in out loading panel
	        this._addLoadingWindowMarkup();
				
					$('lightwindow_contents_inner').insert({
						top: response.responseText
					});

         
					
					this._setStatus(true);
					$('lightwindow_contents_inner').setStyle('overflow: hidden');
					this.resizeTo.height = $('lightwindow_contents_inner').scrollHeight;
					this.resizeTo.width = $('lightwindow_contents_inner').scrollWidth;
					$('lightwindow_contents_inner').setStyle('overflow: inherit');
					this._processWindow();
				}
.bind(this)
			});
		},
		//
    //	Default External link handler for LightWindow
    //
		_defaultExternalHandler: function(e){
		
			var element = Event.element(e);
			element.onclick = (function () {
					 window.open(this.href);
					 return false;
			});
		},
    // 
    //  Wrap everything up
    //
    _finishWindow: function(){
        this._handleFinalWindowAnimation(0);
        this._setupActions();
    }
}; 
/*-----------------------------------------------------------------------------------------------*/
Event.observe(window, 'load', function(){
    initLightWindow();
}, false);

//default lightwindow init function. Can be overridden
function initLightWindow(){
    new lightwindow();
}

