﻿/*
Created By: Chris Campbell
Website: http://particletree.com
Date: 2/1/2006

Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
Modified to make more prototype-y (again) and upgrade to Prototype 1.6.1 by Gareth Evans, Sniper Systems, 28/09/2009
*/


Event.observe(window, 'load', initialize);

var lightbox = Class.create({

    yPos: 0,
    xPos: 0,
    defaultOptions: {
        width: 400,
        height: 400
    },
    setOptions: function(options) {
        this.options = Object.clone(this.defaultOptions);
        Object.extend(this.options, options || {});
    },
    initialize: function(ctrl, options) {
        this.content = ctrl.readAttribute('href');
        Event.observe(ctrl, 'click', function(e) {
            e.stop();
            this.activate.bind(this)();
        } .bind(this));
        if (options == null && window.lightboxOptions) options = window.lightboxOptions;
        this.setOptions(options);
    },

    // Turn everything on - mainly the IE fixes
    activate: function(e) {
        if (Prototype.Browser.IE) {
            this.getScroll();
            this.prepareIE('100%', 'hidden');
            this.setScroll(0, 0);
            this.hideSelects('hidden');
        }
        this.displayLightbox("block");
        valid = this;
    },

    // Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
    prepareIE: function(height, overflow) {
        bod = $$('body').first();
        bod.style.height = height;
        bod.style.overflow = overflow;

        htm = $$('html').first();
        htm.style.height = height;
        htm.style.overflow = overflow;
    },

    // In IE, select elements hover on top of the lightbox
    hideSelects: function(visibility) {
        selects = $$('select');
        for (i = 0; i < selects.length; i++) {
            selects[i].style.visibility = visibility;
        }
    },

    // Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
    getScroll: function() {
        if (self.pageYOffset) {
            this.yPos = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            this.yPos = document.documentElement.scrollTop;
        } else if (document.body) {
            this.yPos = document.body.scrollTop;
        }
    },

    setScroll: function(x, y) {
        window.scrollTo(x, y);
    },

    displayLightbox: function(display) {
        //Prototype.debug('displayLightbox: ' + display);
        $('soverlay').style.display = display;
        $('slightbox').style.display = display;
        if (display != 'none') this.loadInfo();
    },

    // Begin Ajax request based off of the href of the clicked linked
    loadInfo: function() {
        //Prototype.debug('loadInfo ' + this.content);
        var myAjax = new Ajax.Request(this.content,
	{
	    method: 'get',
	    parameters: "r=" + Math.random(),
	    evalJS: 'false',
	    onSuccess: this.processInfo.bind(this),
	    onFailure: function(transport) { alert('Failed to load content.' + transport.responseText); }
	});
    },

    // Display Ajax response
    processInfo: function(response) {
        //Prototype.debug('processInfo: got ajax response');
        var html = response.responseText;
        var beginMarker = '<!--ContentBegin-->';
        var endMarker = '<!--ContentEnd-->';
        if (html.include(beginMarker)) {
            html = html.substring(html.indexOf(beginMarker) + beginMarker.length, html.indexOf(endMarker));
        }
        info = new Element('div', { id: 'lbContent' }).update(html);
        (function() {
            if (window.lightboxOptions != undefined) {
                this.setOptions(window.lightboxOptions);
            }

            if (this.options.height) {
                $('slightbox').setStyle({
                    height: this.options.height + 'px',
                    marginTop: '-' + Math.floor(parseFloat(this.options.height) / 2) + 'px'
                });
            }
            if (this.options.width) {
                $('slightbox').setStyle({
                    width: this.options.width + 'px',
                    marginLeft: '-' + Math.floor(parseFloat(this.options.width) / 2) + 'px'
                });
            }
            if (this.options.onContentLoaded) {
                this.options.onContentLoaded.bind(this).defer();
            }
            $('lbLoadMessage').insert({ before: info });
            $('slightbox').removeClassName('loading').addClassName("done");
            this.actions();
            //Prototype.debug('processInfo: finished processing');
        }).bind(this).defer();
    },

    // Search through new links within the lightbox, and attach click event
    actions: function() {
        lbActions = $('lbContent').select('.lbAction');
        for (i = 0; i < lbActions.length; i++) {
            Event.observe(lbActions[i], 'click', this[lbActions[i].rel].bindAsEventListener(this), false);
            lbActions[i].onclick = function() { return false; };
        }

    },

    // Example of creating your own functionality once lightbox is initiated
    insert: function(e) {
        link = Event.element(e).parentNode;
        Element.remove($('lbContent'));
        var href = link.readAttribute('ajax-href');
        if (href == null) href = link.readAttribute('href');
        var myAjax = new Ajax.Request(
			  href,
			  { method: 'get', parameters: "r=" + Math.random(), onComplete: this.processInfo.bindAsEventListener(this) }
	   );

    },

    // Example of creating your own functionality once lightbox is initiated
    deactivate: function() {
        Element.remove($('lbContent'));

        if (Prototype.Browser.IE) {
            this.setScroll(0, this.yPos);
            this.prepareIE("auto", "auto");
            this.hideSelects("visible");
        }

        this.displayLightbox("none");
    }
});

// Onload, make all links that need to trigger a lightbox active
function initialize() {
    addLightboxMarkup();
    var anchors = document.getElementsByTagName("a");
    // loop through all anchor tags
    for (var i = 0; i < anchors.length; i++) {
        var anchor = anchors[i];
        if (anchor.getAttribute("href") && (anchor.readAttribute("rel") == "lightbox")) {
            var lb = new lightbox(anchor);
        }
    }

}

// Add in markup necessary to make this work. Basically two divs:
// Overlay holds the shadow
// Lightbox is the centered square that the content is put into.
function addLightboxMarkup() {
    var overlay = new Element('div', { id: 'soverlay' }).observe('click', function(e) {
        if (window.valid != undefined)
            window.valid.deactivate();
    });
    overlay.hide();
    var lb = new Element('div', { id: 'slightbox', className: 'loading' }).insert('<div id="lbLoadMessage" style="width:100%; text-align:center;"><img src="/images/loading.gif" class="loading"/></div>');
    lb.hide();
    bod = $$('body').first();
    bod.insert(overlay);
    bod.insert(lb);
}