﻿/* 
LightBox: Client Side functions for LightBox Behaviour
dependancies: prototype.js 1.6.0.2

Sample:


var lb = new LightBox({ 
Title: 'Nice Lightbox!', 
Width: 500, 
Height: 400, 
ContentUrl: 'http', 
CallBack: jsCallbackFunction,    
Assets: { CloseButtonImg: '/App_Themes/Theme1/images/close-btn.gif'}
});
lb.activate();  
      
or <a href="default.aspx" class="lightBoxOpener"></a>            
*/
/*-----------------------------------------------------------------------------------------------*/

Math.sqr = function(x) {
    return x * x;
};

Number.isInteger = function(s) {
    return (s.toString().search(/^-?[0-9]+$/) == 0);
}

Position.getCenter = function(element, parent) {

    element = $(element);
    var w, h, pw, ph;
    var d = element.getDimensions();
    w = d.width;
    h = d.height;
    Position.prepare();
    if (!parent) {
        var ws = Position.getViewPortSize();
        pw = ws.width;
        ph = ws.height;
    } else {
        pw = parent.offsetWidth;
        ph = parent.offsetHeight;
    }
    return { top: (ph / 2) - (h / 2) - Position.deltaY, left: (pw / 2) - (w / 2) - Position.deltaX };
}

Position.center = function(element, parent) {
    var o = Position.getCenter(element, parent);
    element.setStyle({ top: o.top + 'px', left: o.left + 'px' });
}

Position.getViewPortSize = function(win) {

    var winDim = Position.getWindowSize();
    var w = Math.min(document.body.scrollWidth, winDim.width);
    var h = Math.min(document.body.scrollWidth, winDim.height);
    return { width: w, height: h };

}

Position.getWindowSize = function(win) {
    win = win ? win : window;
    var w = win.innerWidth || (win.document.documentElement.clientWidth || win.document.body.clientWidth);
    var h = win.innerHeight || (win.document.documentElement.clientHeight || win.document.body.clientHeight);
    return { width: w, height: h };
}


// Allows you to trigger an event element.  
Object.extend(Event, {
    trigger: function(element, event, fakeEvent) {
        element = $(element);
        fakeEvent = fakeEvent || { type: event };
        this.observers.each(function(cache) {
            if (cache[0] == element && cache[1] == event)
                cache[2].call(element, fakeEvent);
        });
    }
});


var LightBoxDefaultAssets = {
    CloseButtonImg: 'WebResource.axd?d=9aT-1cDcS-QQ2i4sb62m7N-hVOgzft021q0EDhQIPldioTTryNUyuVIsy97aymxFHi4yrqf6Q2AzWPtfFe5_bg2&t=634181478017698750',
    OverlayOpacity: 0.8
};

/* Create static LightBox object */
var LightBox = Class.create();

Object.extend(LightBox, {
    version: '2.0',
    initialised: false,
    loaded: false,
    mask: false,
    current: false,
    dataChanged: false,
    container: false,
    titleBar: false,
    title: false,
    closeLink: false,
    dataHolder: false,
    callBack: false,
    callBackArgs: null,
    maskStyles: {
        display: 'none',
        position: 'fixed',
        'top': 0,
        'left': 0,
        width: '100%',
        height: '100%',
        overflow: 'hidden',
        zIndex: 9998
    },
    maskIEStyles: {
        display: 'none',
        position: 'absolute',
        'top': 0,
        'left': 0,
        width: '100%',
        height: '100%',
        overflow: 'hidden',
        zIndex: 9998
    },
    /* Allow client to set custom Close Button, etc*/
    init: function(assets) {


        this.Assets = {
            CloseButtonImg: 'WebResource.axd?d=9aT-1cDcS-QQ2i4sb62m7N-hVOgzft021q0EDhQIPldioTTryNUyuVIsy97aymxFHi4yrqf6Q2AzWPtfFe5_bg2&t=634181478017698750',
            DataHolderHeader: false
        };
        Object.extend(this.Assets, assets || {});
        this.initialised = true;
    },
    /* Preloads all the HTML elements required by the lightbox*/
    preload: function() {


        if (!LightBox.loaded) {

            if (window.ActiveXObject) {
                window.ie = true;
                temp = navigator.appVersion.split('MSIE');
                ieVer = parseInt(temp[1]);
                window['ie' + ieVer] = true;
            } else if (document.childNodes && !document.all && !navigator.taintEnabled) {
                window.khtml = true;
            } else if (document.getBoxObjectFor != null) {
                window.gecko = true;
            }


            bod = document.getElementsByTagName('body')[0];

            LightBox.mask = new Element('div', { id: 'lightBoxOverlay' });
            LightBox.mask.setStyle(LightBox['mask' + (window.ie ? 'IE' : '') + 'Styles']);

            LightBox.mask.setOpacity(0.6);

            LightBox.container = new Element('div', { id: 'lightBoxContainer' });
            LightBox.container.setStyle({ zIndex: 9999, display: 'none', position: 'absolute', top: 0, left: 0 });

            LightBox.titleBar = new Element('div', { id: 'lightBoxTitleBar' });
            LightBox.titleBar.setStyle({ width: '100%' });

            LightBox.title = new Element('div', { id: 'lightBoxTitle' });
            LightBox.titleBar.appendChild(LightBox.title);

            controls = new Element('div', { id: 'lightBoxControls' });
            LightBox.titleBar.appendChild(controls);

            LightBox.closeLink = new Element('a', { id: 'lightBoxCloseLink', href: '#' }).update('&nbsp;');
            controls.appendChild(LightBox.closeLink);
            Event.observe(LightBox.closeLink, 'click', function(e) {
                Event.stop(e);
                LightBox.close(LightBox.dataChanged);
            }, false);
            LightBox.container.appendChild(LightBox.titleBar);

            var spacer = new Element('div', { 'class': 'clear', 'id': 'lightBoxTitleDataSeperator' });
            spacer.setStyle({ clear: 'both' });
            LightBox.container.appendChild(spacer);

            bod.appendChild(LightBox.mask);
            bod.appendChild(LightBox.container);

            LightBox.loaded = true;

            /* TODO: Get this working
            document.observe('click', (function(event) {
            var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]');
            if (target) {
            event.stop();
            new LightBox({
            Element: target.id
            });
            }
            }).bind(this));
            
            var lbox = document.getElementsByClassName('lightBoxOpener');
            if (lbox != null) {
            for (i = 0; i < lbox.length; i++) {
            LightBoxDefaultAssets['Element'] = lbox[i];
            new LightBox(LightBoxDefaultAssets);
            }
            }
            */
        }
    },
    //
    //  getPageSize()
    //
    getPageSize: function() {

        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;

        if (self.innerHeight) {	// all except Explorer
            if (document.documentElement.clientWidth) {
                windowWidth = document.documentElement.clientWidth;
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if (xScroll < windowWidth) {
            pageWidth = xScroll;
        } else {
            pageWidth = windowWidth;
        }

        return [pageWidth, pageHeight];
    },
    setTitle: function(title) {
        LightBox.title.innerHTML = title;

    },

    open: function(options) {

        if (options != null) {
            if (LightBox.dataHolder)
                LightBox.container.removeChild(LightBox.dataHolder);
            LightBox.current = new LightBox(options);
        }

        if (LightBox.current)
            LightBox.current.activate();


        return LightBox.current;
    },

    close: function(executeCallBack, args) {

        if (LightBox.current) {
            LightBox.current.deactivate();
        }

        var runCallBack = ((executeCallBack && executeCallBack == true) || LightBox.dataChanged == true);

        if (LightBox.callBack && runCallBack) {
            var type = typeof LightBox.callBack;
            var myArgs = args || LightBox.callBackArgs;
            if (type == 'string') {

                var execString = myArgs != null ? LightBox.callBack.replace('()', '(' + myArgs + ')') : LightBox.callBack;
                eval(execString);
            } else
                LightBox.callBack(myArgs);
        }

        LightBox.callBack = false;
        LightBox.callBackArgs = null;
    },

    toggleSelects: function(visibility) {
        $A(document.getElementsByTagName('select')).each(function(select) {
            select.style.visibility = visibility;
        });
    },

    setDataHolder: function(options) {

        var inIframe = (options.Method == 'IFRAME') ? true : false;
        var tagName = (inIframe == true) ? 'iframe' : 'div';
        if (LightBox.dataHolder != false)
            LightBox.dataHolder.remove();

        //LightBox.dataHolder = new Element(((inIframe == true) ? 'iframe' : 'div'), { id: 'popupFrame' }); //, style:'width:100%;height:100%'
        LightBox.dataHolder = new Element('div', { id: 'lightBoxDataHolder' }); //, style:'width:100%;height:100%'
        LightBox.dataHolder.setStyle({ width: '100%', height: '100%', overflow: 'hidden', position: 'relative', margin: 0 });
        LightBox.container.insert({ bottom: LightBox.dataHolder });

        if (inIframe) {
            LightBox.iFrame = true;
        } else {
            LightBox.iFrame = false;
        }
        LightBox.dataChanged = false;
    }
});


/* Create LightBox Instance */
Object.extend(LightBox.prototype = {

    initialize: function(options) {

        this.setOptions(options);

        this.onActivate = this.activate.bindAsEventListener(this);
        this.onSetPopTitle = this.setPopTitle.bindAsEventListener(this);
        this.onProcessInfo = this.processInfo.bindAsEventListener(this);

        if (this.Options.Element != null) {
            if (this.Options.EventTrigger == 'DBLCLICK') {
                Event.observe(this.Options.Element, 'dblclick', this.onActivate, false);
                this.Options.Element.ondblclick = function() { return false; };
            } else {
                Event.observe(this.Options.Element, 'click', this.onActivate, false);
                this.Options.Element.onclick = function() { return false; };
            }
        }

        if (this.Options.AutoActivate == true) { this.activate(); }

    },

    setOptions: function(options) {
        this.Options = {
            Element: null,
            ContentUrl: '#',
            Title: 'Content Editor',
            Width: '800px',
            Height: '550px',
            Method: 'IFRAME',
            CallBack: null,
            EventTrigger: 'CLICK',
            Parameters: '',
            Position: 'absolute',
            OffsetTop: 0,
            AutoActivate: false,
            Animated: false,
            Duration: 1.2,
            zIndex: 9998,
            Assets: { CloseButtonImg: 'WebResource.axd?d=9aT-1cDcS-QQ2i4sb62m7N-hVOgzft021q0EDhQIPldioTTryNUyuVIsy97aymxFHi4yrqf6Q2AzWPtfFe5_bg2&t=634181478017698750' },
            beforeOpen: Prototype.emptyFunction,
            afterOpen: Prototype.emptyFunction,
            beforeClose: Prototype.emptyFunction,
            afterClose: Prototype.emptyFunction,
            onSuccess: Prototype.emptyFunction,
            onFailure: Prototype.emptyFunction,
            onException: Prototype.emptyFunction,
            RenderTitleDataSeperator: true

        };

        Object.extend(this.Options, options || {});
        this.Options.Method = this.Options.Method.toUpperCase();
        this.Options.EventTrigger = this.Options.EventTrigger.toUpperCase();

        if (this.Options.Element != null && typeof this.Options.Element == 'string') {
            this.Options.Element = $(this.Options.Element);
        }

        if (this.Options.ContentUrl == '#') {
            if (this.Options.Element.href && this.Options.Element.href.length > 0 && this.Options.Element.href != '#') {
                this.Options.ContentUrl = this.Options.Element.href;
            }
        }
        if (typeof this.Options.Parameters == 'string') {
            this.Options.Parameters = this.Options.Parameters.toQueryParams();
        }

        if (Number.isInteger(this.Options.Width)) {
            this.Options.Width += 'px';
        }

        if (Number.isInteger(this.Options.Height)) {
            this.Options.Height += 'px';
        }
        if (typeof Scriptaculous == 'undefined') {
            this.Options.Animated = false;
        }

    },
    /* Turn everything on*/
    activate: function() {

        //Event.observe(window,'resize',this.position,false);
        //Event.observe(window,'scroll',this.position,false);
        this.notify('beforeOpen');
        if (!LightBox.current)
            this.display('block');
        this.notify('afterOpen');
    },
    /* Close Lightbox window */
    deactivate: function() {

        this.notify('beforeClose');
        //Event.stopObserving(window,'resize',this.position,false);
        //Event.stopObserving(window,'scroll',this.position,false);
        if (LightBox.current != false)
            this.display('none');

        this.notify('afterClose');
    },
    /* display this instance of the Modal Dialog */

    display: function(displayMode) {

        if (!LightBox.initialised)
            LightBox.init(this.Options.Assets);

        var arrayPageSize = LightBox.getPageSize();
        LightBox.mask.setStyle({ display: displayMode, width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px', zIndex: this.Options.zIndex });


        //var pageDimensions = Position.getViewPortSize();
        //LightBox.mask.setStyle({display: display, height: pageDimensions.height + 'px', width: pageDimensions.width + 'px', zIndex: this.Options.zIndex });

        var titleBarHeight = LightBox.titleBar.getHeight();

        if (displayMode != 'none') {
            LightBox.closeLink.update('<img id=\'lightBoxCloseImage\' src=\'' + LightBox.Assets.CloseButtonImg + '\' alt=\'Close\'/>');

            LightBox.current = this;
            LightBox.container.setStyle({ width: this.Options.Width, height: this.Options.Height, display: displayMode, zIndex: this.Options.zIndex + 1 });
            //Position.center(LightBox.loadingPlaceHolder);
            LightBox.callBack = this.Options.CallBack;

            LightBox.setDataHolder(this.Options);
            this.loadContent();



            /*Resize content to get rid of scroll bars*/
            var maxWidth = parseInt(this.Options.Width.toString().replace('px', ''));
            var maxHeight = parseInt(this.Options.Height.toString().replace('px', ''));
            var hPad = Math.max(LightBox.dataHolder.offsetWidth - maxWidth, 0);
            var vPad = LightBox.titleBar.getHeight() + Math.max(LightBox.dataHolder.offsetHeight - maxHeight, 0); ;

            var dhWidth = (maxWidth - hPad);
            var dhHeight = (maxHeight - vPad);

            LightBox.dataHolder.setStyle({ width: dhWidth + 'px', height: dhHeight + 'px' });

            var pageDim = document.viewport.getDimensions();
            var pageOffset = document.viewport.getScrollOffsets();

            // calculate top and left offset for the lightbox
            var lightboxTop = (pageDim.height - dhHeight) / 2 + pageOffset.top;
            var lightboxLeft = (pageDim.width - dhWidth) / 2 + pageOffset.left;

            // Show/hide the title data seperator
            var titleDataSeperator = LightBox.container.select("[id=\"lightBoxTitleDataSeperator\"]")[0];
            titleDataSeperator.style.display = this.Options.RenderTitleDataSeperator ? "" : "none";

            //
            if (this.Options.Animated) {

                //LightBox.container.setStyle({ height: vPad + 'px', left: d.left + 'px', top: d.top + 'px', overflow: 'hidden' }).show();
                LightBox.container.setStyle({ height: vPad + 'px', left: lightboxLeft + 'px', top: lightboxTop + 'px', overflow: 'hidden' }).show();

                var newCss = 'height:' + this.Options.Height + ';overflow:auto';
                new Effect.Morph(LightBox.container, {
                    style: newCss,
                    duration: this.Options.Duration,
                    afterFinish: function() { LightBox.dataHolder.setStyle({ display: 'block' }); }
                });

            } else {

                LightBox.dataHolder.show();
                //LightBox.container.setStyle({ top: d.top + 'px', left: d.left + 'px' }).show();
                LightBox.container.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();

            }



        } else {

            /*if (this.Options.Animated) {
            var newCss = 'height:' + titleBarHeight + 'px;';
            new Effect.Morph(LightBox.container, {
            style: newCss,
            duration: this.Options.Duration,
            afterFinish: function() { LightBox.container.setStyle({ display: 'none' }); }
            });
            } else {*/
        LightBox.container.setStyle({ display: displayMode });
            //}

            if (LightBox.dataHolder) {

                if (this.Options.Method == 'IFRAME')
                    Event.stopObserving(LightBox.dataHolder, 'load', this.onSetPopTitle, false);
                LightBox.dataHolder.remove();
                LightBox.dataHolder = false;
            }
            LightBox.current = false;
        }

        if (window.ie && !window.ie7) {
            LightBox.toggleSelects((displayMode != 'none') ? 'hidden' : 'visible');
        }
        return false;
    },

    /* Begin Ajax request based off of the href of the clicked linked */
    loadContent: function() {

        LightBox.setTitle(this.Options.Title);
        //LightBox.loadingPlaceHolder.setStyle({display:'block'});
        if (this.Options.Method == 'AJAX') {
            var myAjax = new Ajax.Request(
                this.Options.ContentUrl, {
                    method: 'post',
                    parameters: '',
                    onComplete: this.onProcessInfo
                }
		    );
        } else {

            //var iframe = '<iframe src="' + this.Options.ContentUrl + '" name="lightBoxIframe" id="lightBoxIframe" width="100%" marginwidth="0" height="100%" marginheight="0" scrolling="auto" frameborder="0" ></iframe>';
        var iframe = new Element('iframe', { src: 'WebResource.axd?d=9aT-1cDcS-QQ2i4sb62m7N-hVOgzft021q0EDhQIPlfu1i13SWiiV_h6zaPopeuftXgGl9KIfPK1SeToZR4yHCP2Njqs95awcWMKHRf8YLY1&t=634181478017698750', id: 'lightBoxIframe', name: 'lightBoxIframe', width: '100%', marginwidth: '0', height: '100%', marginheight: '0', scrolling: 'auto', frameborder: '0', border: '0' });
            //var iframe = '<iframe src="' + this.Options.ContentUrl + '" name="lightBoxIframe" id="lightBoxIframe" width="100%" marginwidth="0" height="100%" marginheight="0" scrolling="auto" frameborder="0" ></iframe>';

            LightBox.dataHolder.appendChild(iframe);
            iframe.src = this.Options.ContentUrl;
            //LightBox.dataHolder.update(iframe)
            Event.observe(LightBox.dataHolder, 'load', this.onSetPopTitle, false);
        }

    },

    setPopTitle: function() {
        LightBox.setTitle(this.Options.Title);

    },

    /* Display Ajax response*/
    processInfo: function(response) {

        //LightBox.setTitle(this.Options.Title);
        LightBox.setTitle('Loading');
        //LightBox.loadingPlaceHolder.setStyle({display:'none'});
        LightBox.dataHolder.innerHTML = response.responseText;
        this.actions();

    },

    /* Search through new links within the lightbox, and attach click event*/
    actions: function() {
        if (this.Options.Method == 'AJAX') {
            lbActions = document.getElementsByClassName('LightBoxCloser');
            for (i = 0; i < lbActions.length; i++) {
                Event.observe(lbActions[i], 'click', function() { LightBox.close(true); }, false);
                lbActions[i].onclick = function() { return false; };
            }
        }
    },
    notify: function(event_name) {
        try {
            if (this.Options[event_name])
                return [this.Options[event_name].apply(this.Options[event_name], $A(arguments).slice(1))];
        } catch (e) {
            if (e != $break)
                throw e;
            else
                return false;
        }
    }

});

/* Initialise the LightBox static object */
Event.observe(window, 'load', LightBox.preload, false);




if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();