/*
 * SYNOPSIS
 *
 * // for image popup
 * new Lightbox().setup();
 *
 * // for html popup
 * <a onclick="new Lightbox({ url: '/path/to/html.html' }).show()">show popup</a>
 *
 *
 * Author  : murase@kayac.com
 * Original: http://www.huddletogether.com/projects/lightbox/
 *
 */

var Lightbox = Class.create();
Lightbox.config = $H();

// Taken from http://www.eight.nl/files/leightbox/
Lightbox.getPageSize = function() {
    var xScroll, yScroll;
    var windowWidth, windowHeight;
    var pageWidth, pageHeight;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = document.body.scrollWidth;
        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;
    }

    if (self.innerHeight) {// all except Explorer
        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 = windowWidth;
    }
    else {
        pageWidth = xScroll;
    }

    Lightbox.windowWidth  = windowWidth;
    Lightbox.windowHeight = windowHeight;
    Lightbox.pageWidth    = pageWidth;
    Lightbox.pageHeight   = pageHeight;
};


Lightbox.prototype = {
    callback: null,
    initialize: function(options) {
        options = options || {};
        // set default value
        this.config({
            lightbox_id:   Lightbox.config.lightbox_id   || 'lightbox',
            overlay_id:    Lightbox.config.overlay_id    || 'lightbox_overlay',
            loading_image: Lightbox.config.loading_image || 'loading.gif',
            loading_id:    Lightbox.config.loading_id    || 'lightbox_loader',
            container_id:  Lightbox.config.container_id  || 'lightbox_container',
            container_width: Lightbox.config.container_width,
            container_height: Lightbox.config.container_height,
            ajax_class: Lightbox.config.ajax_class || "Ajax.Request"
        });

        this.config(options);
    },

    config: function(config) {
        if (!this._config) this._config = $H();

        if (config) {
            config = $H( config );
            try {
                for (var i=0; i<config.keys().length; i++) {
                    var key = config.keys()[i];
                    this._config[key] = config[key];
                };
            } catch (e) {}
        }

        return this._config;
    },

    setup: function() {
        Event.observe( window, 'load', this.setup_anchors.bind(this) );
    },

    setup_anchors: function() {
        var anchors = $A( document.getElementsByTagName('a') );
        for (var i=0; i<anchors.length; i++) {
            anchor = anchors[i];
            if ( anchor.href && anchor.rel == 'lightbox' ) {
                anchor.onclick = this.show.bind(this, anchor);
            }
        };

        if (!$(this.config['overlay_id'] || 'overlay')) {
            this._init();
        }
    },

    update_overlay_size: function() {
        Lightbox.getPageSize();

        var overlay = $( this.config().overlay_id );
        overlay.style.height = (Lightbox.pageHeight + 'px');
        overlay.style.minHeight = (Lightbox.pageHeight + 'px');

        return overlay;
    },

    fix_overlay_size: function(element) {
        var overlay = this.update_overlay_size();
        var overlay_height = overlay.style.height.match(/(\d+)/)[1];
        var content_height;
        try {
            content_height = element.offsetHeight;
        } catch (e) {}

        if (!overlay_height || overlay_height < content_height) {
            overlay.style.height = content_height + 'px';
        }
    },

    show: function(anchor) {
        if ( !$( this.config().overlay_id ) ) this._init();

        var yPos = this.getScroll();
        var overlay = this.update_overlay_size();
        overlay.style.display = 'block';

        var loadingImage = $$('#'+this.config().loading_id+' img');// cssQuery('img', $( this.config().loading_id ) );
        if (loadingImage[0]) {
            loadingImage = loadingImage[0];
            loadingImage.style.top = (yPos + ((Lightbox.windowHeight - 35 - loadingImage.height) / 2) + 'px');
            loadingImage.style.left = (((Lightbox.pageWidth - 20 - loadingImage.width) / 2) + 'px');
            loadingImage.style.display = 'block';
            $(this.config().loading_id).style.display = 'block';
        }

        // FIXME dirty hack
        if (document.all) {
            var selectBoxes = $A( document.getElementsByTagName('select') );
            selectBoxes.each(function(selectBox) {
                selectBox.style.visibility = 'hidden';
            } );
            var selectBoxes = $A( document.getElementsByTagName('iframe') );
            selectBoxes.each(function(selectBox) {
                selectBox.style.visibility = 'hidden';
            } );
        }

        if (typeof anchor == 'object' && anchor.href) {
            if (anchor["src"]) {
                anchor["href"] = anchor["src"];
            }

            var preload = new Image();
            var preload_onload = function() {
                var container = $( this.config().container_id );
                Element.update(container, '<div class="lightBOXblueBG" id="lightbox_image_body"><div class="blueCLOSE"><img src="/image/common/blue_close.gif" alt="閉じる" name="lightbox_close_bot" id="lightbox_close_bot" onmouseover="MM_swapImage(\'lightbox_close_bot\',\'\',\'/image/common/blue_close_f2.gif\',1)" onmouseout="MM_swapImgRestore()" onclick="new Lightbox().hide(); return false;" height="24" width="24" /></div></div>');

                var image = document.createElement('img');
                image.src = anchor.href;
                image.width = preload.width;
                image.height = preload.height;
                image.style.border = 'none';
                //image.onclick = this.hide.bind(this);
                var lightboxTop = (yPos + (Lightbox.windowHeight - 35 - preload.height) / 2);
                var lightboxLeft = ((Lightbox.pageWidth - 20 - preload.width) / 2);

                container.style.position = 'absolute';
                container.style.zIndex   = '10000';
                container.style.top = (lightboxTop < 0) ? '0px' : lightboxTop + 'px';
                container.style.left = (lightboxLeft < 0) ? '0px' : lightboxLeft + 'px';
                container.style.display = 'block';

                $('lightbox_image_body').appendChild(image);

                var loader = $(this.config().loading_id);
                if (loader) loader.style.display = 'none';
            }
            preload.onload = preload_onload.bind(this);
            preload.src = anchor.href;
        }
        else if (this.config().url) {
            eval(["new "+this.config().ajax_class+"(",
                    "    Flash.require(8,0,0) ? this.config().url : '/static/flash8_or_above_is_required.xml',",
                    "{",
                    "    method: 'get',",
                    "    onSuccess: this.onCompleteAjax.bind(this)",
                    "}",
                    ");"].join("\n")
                );
        }
        return false;
    },

    hide: function(effect) {
        // FIXME dirty hack
        if (document.all) {
            var selectBoxes = $A( document.getElementsByTagName('select') );
            selectBoxes.each(function(selectBox) {
                selectBox.style.visibility = 'visible';
            } );
            var selectBoxes = $A( document.getElementsByTagName('iframe') );
            selectBoxes.each(function(selectBox) {
                selectBox.style.visibility = 'visible';
            } );
        }

        var overlay = $( this.config().overlay_id );
        if (overlay) overlay.style.display = 'none';

        var loader  = $$('#'+this.config().loading_id+' img'); //cssQuery('img', $( this.config().loading_id ));
        if (loader && loader[0])
            loader[0].style.display = 'none';

        var container = $( this.config().container_id );
        container.style.cssText = '';
        if (container) {
            container.style.display = 'none';
            container.lightbox = null;
        }

        this.update_overlay_size();

        return false;
    },

    centalize: function(element, rect) {
        if (!rect.width && !rect.height)
            return;

        var yPos = this.getScroll();
        var lightboxTop = (yPos + (Lightbox.windowHeight - 35 - rect.height) / 2);
        var lightboxLeft = ((Lightbox.pageWidth - 20 - rect.width) / 2);

        element.style.position = 'absolute';
        element.style.zIndex   = '9999';
        element.style.top = (lightboxTop < 0) ? '0px' : lightboxTop + 'px';
        element.style.left = (lightboxLeft < 0) ? '0px' : lightboxLeft + 'px';
        element.style.width = rect.width+'px';
        element.style.height = rect.height+'px';
    },

    getScroll: function() {
        var yScroll;

        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
        }
        else if ( document.documentElement && document.documentElement.scrollTop ) { // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
        }
        else if (document.body) { // all other Explorers
            yScroll = document.body.scrollTop;
        }

        return yScroll;
    },

    setScroll: function(x, y){
        window.scrollTo(x, y);
    },

    onCompleteAjax: function(request) {
        var response;
        var content;

        try {
            response = request.responseXML.lastChild;
        } catch(e) { }

        if (response) {
            for (var i = 0; i < response.childNodes.length; i++) {
                if ( response.childNodes[i].nodeName.match(/cdata/) ) {
                    content = response.childNodes[i].nodeValue;
                    break;
                }
            }
        }
        else if (typeof(request) == "string") {
            var m = request.match(/<!\[CDATA\[((?:.|[\n])+)\]\]>/);
            if (m) content = m[1];
        }

        if (content) {
            var yPos = this.getScroll();
            Lightbox.getPageSize();

            var container = $( this.config().container_id );
            Element.update(container, content);

            if (this.config().container_style)
                container.style.cssText = this.config().container_style;

            if (this.config().container_width && this.config().container_height) {
                this.centalize( container, { width: this.config().container_width, height: this.config().container_height } );
            }

            container.style.display  = 'block';
            container.lightbox = this;

            var loader = $(this.config().loading_id);
            if (loader) loader.style.display = 'none';

            try {
                this.fix_overlay_size( $$('#'+container.id+' .lightBOXbg')[0] ); //cssQuery('.lightBOXbg', container)[0] );
            } catch (e) {}

            // setTimeout( this.fix_overlay_size( cssQuery('.lightBOXbg', container)[0] ).bind(this), 200 );
            this.callback();
        }
    },

    _init: function() {
        var lightbox = document.createElement('div');

        lightbox.id = this.config().lightbox_id;

        var overlay = document.createElement('div');

        overlay.id             = this.config().overlay_id;
        //overlay.onclick        = this.hide.bind(this);
        overlay.style.position = 'absolute';
        overlay.style.top      = '0';
        overlay.style.left     = '0';
        overlay.style.zIndex   = '90';
        overlay.style.width    = '100%';
        overlay.style.display  = 'none';

        //lightbox.appendChild( overlay );

        var preloader = new Image();
        var preloader_onload = function() {
            var loader = document.createElement('div');
            loader.id = this.config().loading_id;
            loader.style.display = 'none';

            var loader_link = document.createElement('a');
            loader_link.href = '#';
            loader_link.onclick = this.hide.bind(this);

            var loader_image = document.createElement('img');
            loader_image.src = this.config().loading_image;
            loader_image.width = preloader.width;
            loader_image.height = preloader.height;
            loader_image.style.position = 'absolute';
            loader_image.style.zIndex = '150';
            loader_image.style.border = 'none';
            loader_image.style.display = 'none';

            loader_link.appendChild( loader_image );
            loader.appendChild( loader_link );
            lightbox.appendChild( loader );

            preloader.onload = function () {}; //clear onLoad, as IE will flip out w/animated gifs

            return false;
        };
        preloader.onload = preloader_onload.bind(this);
        preloader.src = this.config().loading_image;

        var container = document.createElement('div');
        container.id = this.config().container_id;
        container.style.display = 'none';

        lightbox.appendChild(container);
        lightbox.appendChild(overlay);

        document.body.appendChild(lightbox);
    },

    pause: function(numberMillis) {
        var now = new Date();
        var exitTime = now.getTime() + numberMillis;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return;
        }
    },

    dummy: null
};

function printfire()
{
    if (document.createEvent)
        {
            printfire.args = arguments;
            var ev = document.createEvent("Events");
            ev.initEvent("printfire", false, true);
            dispatchEvent(ev);
        }
}
