/*  =Lightbox
----------------------------------------------- */
var Lightbox = [];
var Lightbox = function() {

    var gModal = null;
    var gOuter = null;
    var gInner = null;
    var gReturnFunc;
    var gPopupIsShown = false;

    /*  =Initialize
    ----------------------------------------------- */
    function init() {
        // Add onclick handlers to 'a' elements of class modalwindow or modalwindow-width-height
        var elms = document.getElementsByTagName('a');
        for (i = 0; i < elms.length; i++) {
            if (elms[i].className.indexOf("modalwindow") >= 0) {
                elms[i].onclick = function() {
                    Carousel.addEvent(Carousel.ul, 'mouseout', Carousel.pause_carousel);

                    // default width and height
                    var width = 530;
                    var height = 400;
                    // Parse out optional width and height from className
                    var startIndex = this.className.indexOf("modalwindow");
                    var endIndex = this.className.indexOf(" ", startIndex);
                    if (endIndex < 0) {
                        endIndex = this.className.length;
                    }
                    var clazz = this.className.substring(startIndex, endIndex);
                    params = clazz.split('-');
                    if (params.length == 3) {
                        width = parseInt(params[1]);
                        height = parseInt(params[2]);
                    }
                    showModal(this.href,width,height,null); return false;
                }
            }
        }
        addEvent(window, "resize", centerModal);
        addEvent(window, "scroll", centerModal);
        //window.onscroll = centerModal;

        // Close any other windows that may be open.
        for (var index = 0; index < Lightbox.length; index++) {
            Lightbox[index].destroy();
        }

        // If the user presses "esc" hide the lightbox
        addEvent(document, "keydown", function(e) {
            if (e && e.keyCode == 27) {
                destroy();
            }
        });
    };

    /*
     * @argument url - url to display
     * @argument width - int in pixels
     * @argument height - int in pixels
     * @argument returnFunc - function to call when returning true from the window.
     */
    function showModal(url, width, height, returnFunc) {
        // Create a modal element (for the page mask).
        var body = document.getElementsByTagName('body')[0];
        var modal = document.createElement('div');
        modal.id = 'modal';

        // Create elements to represent the modal window
        var outer = document.createElement('div');
        outer.id = 'outer';
        inner = document.createElement("div");
        inner.id = "inner";
        body.appendChild(modal);
        addEvent(modal, "click", onCloseButtonClick);
        body.appendChild(outer);
        outer.appendChild(inner);

        // Create a close button.
        var closeButton = document.createElement("a");
        closeButton.className = "close";
        closeButton.href = "#close";
        //closeButton.appendChild(document.createTextNode("Close"));
        outer.appendChild(closeButton);
        addEvent(closeButton, "click", onCloseButtonClick);

        gModal = document.getElementById("modal");
        gOuter = document.getElementById("outer");
        gInner = document.getElementById("inner");

        gPopupIsShown = true;
        gModal.style.display = "block";
        gOuter.style.display = "block";

        centerModal(width, height);

        gOuter.style.width = width + "px";
        gOuter.style.height = height + "px";

        gInner.style.width = (width - 20) + "px";
        gInner.style.height = (height - 50) + "px";
        gInner = sendRequest(url, inner.id);

        gReturnFunc = returnFunc;
    };
    function centerModal(width, height) {
        var gi = 0;
        if (gPopupIsShown == true) {
            if (width == null || isNaN(width)) {
                width = gOuter.offsetWidth;
            }
            if (height == null) {
                height = gOuter.offsetHeight;
            }
            var fullHeight = getViewportHeight();
            var fullWidth = getViewportWidth();
            var scLeft,scTop;
            if (self.pageYOffset) {
                scLeft = self.pageXOffset;
                scTop = self.pageYOffset;
            } else if (document.documentElement && document.documentElement.scrollTop) {
                scLeft = document.documentElement.scrollLeft;
                scTop = document.documentElement.scrollTop;
            } else if (document.body) {
                scLeft = document.body.scrollLeft;
                scTop = document.body.scrollTop;
            }
            gModal.style.height = fullHeight + "px";
            gModal.style.width = fullWidth + "px";
            gModal.style.top = scTop + "px";
            gModal.style.left = scLeft + "px";
            window.status = gModal.style.top + " " + gModal.style.left + " " + gi++;
            var topMargin = scTop + (125); //+ ((fullHeight - height) / 2);
            if (topMargin < 0) { topMargin = 0; }
            gOuter.style.top = topMargin + "px";
            gOuter.style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
        }
    };

    /*
     * @argument callReturnFunc - bool - determines if we call the return function specified
     * @argument returnVal - anything - return value
     */
    function onCloseButtonClick(callReturnFunc) {
        cancelClick(callReturnFunc);
        gPopupIsShown = false;
        if (gModal == null) {
            return;
        }
        destroy();
        Carousel.play_carousel();
    };
    function destroy() {
        if (gModal && gModal.parentNode) gModal.parentNode.removeChild(gModal);
        if (gOuter && gOuter.parentNode) gOuter.parentNode.removeChild(gOuter);
    };

    /*  =Gets the full width/height because it's different for most browsers
    ----------------------------------------------- */
    function getViewportHeight() {
        if (window.innerHeight!=window.undefined) return window.innerHeight;
        if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
        if (document.body) return document.body.clientHeight;
        return window.undefined;
    };
    function getViewportWidth() {
        if (window.innerWidth!=window.undefined) return window.innerWidth;
        if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth;
        if (document.body) return document.body.clientWidth;
        return window.undefined;
    };

    /*  =Helper Methods
    ----------------------------------------------- */
    /*
     * @argument obj - the object to attach event to
     * @argument type - name of the event
     * @argument fn - function to call
     */
    function addEvent(obj, type, fn) {
        if ( obj.attachEvent ) {
         obj['e'+type+fn] = fn;
         obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
         obj.attachEvent( 'on'+type, obj[type+fn] );
        } else
         obj.addEventListener( type, fn, false );
    };
    function removeEvent( obj, type, fn ) {
      if ( obj.detachEvent ) {
        obj.detachEvent( 'on'+type, obj[type+fn] );
        obj[type+fn] = null;
      } else
        obj.removeEventListener( type, fn, false );
    };
    function removeClass(o,c) {
        var rep=o.className.match(' '+c)?' '+c:c;
        o.className=o.className.replace(rep,'');
    };
    function addClass(o,c) {
        var test = new RegExp("(^|\\s)" + c + "(\\s|$)").test(o.className);
        if(!test){o.className+=o.className?' '+c:c;}
    };
    function cancelClick(e) {
        if (window.event) {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
        }
        if (e && e.stopPropagation && e.preventDefault) {
            e.stopPropagation();
            e.preventDefault();
        }
    };

    /*  =Ajax
    ----------------------------------------------- */
    function sendRequest(url, target) {
        // Create Ajax loader icon.
        var ajax_load = document.createElement('img');
        addClass(ajax_load, 'loader');
        ajax_load.src = 'images/lightbox/ajax-loader.gif';
        ajax_load.alt = 'Retrieving Data...';
        gInner.appendChild(ajax_load);

        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (req != undefined) {
            req.onreadystatechange = function() {onResponse(url, target);};
            req.open("GET", url, true);
            req.send("");
        }
    };
    function onResponse(url, target) {
        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200) { // only if "OK"
                document.getElementById(target).innerHTML = req.responseText;
                /*  =Since the DOM has already been loaded the <a> tags in the lightbox
                   are not in the global jquery object... so re-fire the script...
                ----------------------------------------------- */
                Behavior.init_external_links();
            } else {
                document.getElementById(target).innerHTML=" onResponse Error:\n"+ req.status + "\n" +req.statusText;
            }
        }
    };

    init();
}();

