// NOTE: the yui tooltip has the old SELECT/div bug where the SELECT pokes through the div that is positioned over it.  It supposed to inherit a fix for this from Overlay,
// but it isn't working.  For now, this code will depend on jquery bgiframe being loaded and will use bgiframe to fix the IE6 bug

tooltipGrid = function() {
    var e = YAHOO.util.Event;
    var tooltipId = 'thumb_grid';
    var grid;
    var cachedResponseText = new Object();
    var preloadedImages = new Array();
    var thumbs;

    function adjustTooltip(toolDiv, context) {
        //      YAHOO.util.Dom.setX(tooltipDiv, YAHOO.util.Dom.getX(context) + context.offsetWidth + 20);
//        YAHOO.util.Dom.setY(tooltipDiv, YAHOO.util.Dom.getY(tooltipDiv) + 10);

        // make sure the grid doesn't go beyond the bottom of the viewport
        var bottom = YAHOO.util.Dom.getY(toolDiv) + toolDiv.offsetHeight;

        if (bottom > YAHOO.util.Dom.getDocumentScrollTop() + YAHOO.util.Dom.getViewportHeight()) {
            YAHOO.util.Dom.setY(toolDiv, YAHOO.util.Dom.getDocumentScrollTop() + YAHOO.util.Dom.getViewportHeight() - (toolDiv.offsetHeight + 5));
        }

        var contextBottom = YAHOO.util.Dom.getY(context) + context.offsetHeight;
        var tooltipTop = YAHOO.util.Dom.getY(toolDiv);
        YAHOO.log("bottom: " + contextBottom + " top: " + tooltipTop);
        if ( tooltipTop > contextBottom ) {
            YAHOO.util.Dom.setY( toolDiv, contextBottom - 30 );
        }
    }


    function initTooltips(id) {
        if (!thumbs) {
            thumbs = YAHOO.util.Dom.getElementsByClassName('thumbnail', 'td', id);
        }
        var container = document.getElementById(id);
        var tooltipDiv = document.createElement('div');
        tooltipDiv.id = tooltipId;
        container.appendChild(tooltipDiv);
        
        grid = new YAHOO.widget.PersistentTooltip(tooltipDiv, {
                                                          context: thumbs,
                                                          text: YAHOO.widget.PersistentTooltip.loadingMessage,
                                                          preventcontextoverlap: true,
                                                          constraintoviewport: true,
                                                          autodismissdelay: 500000,
                                                          hidedelay:1000,
                                                          initMsgDiv: "grid_init_msg",
                                                          initMsgText: "hover over thumbnails to see more images",
                                                          iframe: false
                                                          }
            );

        grid.contextMouseOverEvent.subscribe(
            function(type, args) {
                var context = args[0];
                var e = args[1];
                var mouseOverTarget = YAHOO.util.Event.getTarget(e);

                if (mouseOverTarget.tagName != 'IMG') {
                    return false;
                }
                if (YAHOO.util.Dom.hasClass(context, 'no_images')) {
                    grid.hide();
                    grid.cfg.setProperty("text", "");
                    return false;
                } else {
                    grid.cfg.setProperty("text", YAHOO.widget.PersistentTooltip.loadingMessage);
                }
            }
            );

        grid.contextTriggerEvent.subscribe(
            function(type, args) {
                try {
                YAHOO.log("in trigger event");
                var context = args[0];
            
                if (!context) {
                    return;
                }

                var oid = oidFromContextId(context);

                if (cachedResponseText[oid]) {
                    this.cfg.setProperty("text", cachedResponseText[oid]);
                    this.show();
                    YAHOO.util.Dom.setX(tooltipDiv, YAHOO.util.Dom.getX(context) + context.offsetWidth + 20);
                                       YAHOO.util.Dom.setY(tooltipDiv, YAHOO.util.Dom.getY(tooltipDiv) + 10);
                    adjustTooltip(this.element, context);
                    if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie < 7) {
                        $("#" + this.element.id).bgiframe();
                    }
                } else {
                    YAHOO.log("about to send request for oid " + oid);
                    sendAjaxRequest(oid, tooltipDiv, this);
                    YAHOO.util.Dom.setX(tooltipDiv, YAHOO.util.Dom.getX(context) + context.offsetWidth + 20);
                    YAHOO.util.Dom.setY(tooltipDiv, YAHOO.util.Dom.getY(tooltipDiv) + 10);
                    adjustTooltip(this.element, context);
                }
                } catch (e) { YAHOO.log("trigger error: " + e.message) }
            });
    } 

    function oidFromContextId(context) {
        var regex = new RegExp('thumb_(\\d+)');
        var oid = context.id.replace(regex, "$1");
        return oid ? oid : '';
    }

    function sendAjaxRequest(oid, tooltipDiv, grid, callback) {
            YAHOO.log("in sendAjaxRequest");
            if (!callback) {
                // defaults to displaying the response in the div
                callback =      {
                    success: function(o) {
                        YAHOO.log("tool: " + o.argument.tool);
                        o.argument.tool.cfg.setProperty("text", o.responseText);
                        o.argument.tool.show();
YAHOO.util.Dom.setX(tooltipDiv, YAHOO.util.Dom.getX(tooltipDiv.context) + tooltipDiv.context.offsetWidth + 20);
                                       YAHOO.util.Dom.setY(tooltipDiv, YAHOO.util.Dom.getY(tooltipDiv) + 10);
                        adjustTooltip(o.argument.toolDiv, o.argument.tool._context);
                        if (YAHOO.env.ua.ie > 5 && YAHOO.env.ua.ie < 7) {
                            $("#" + o.argument.toolDiv.id).bgiframe();
                        }
                        cachedResponseText[o.argument.oid] = o.responseText;
                    },
                    failure: function(o) {
                        o.argument.tool.cfg.setProperty("text", "Error fetching text"); 
                    },
                    argument: { tool: grid, toolDiv: tooltipDiv, oid: oid }
                };
            }
            var foo = YAHOO.util.Connect.asyncRequest('GET',
                                                      thumbnailGridAjaxUrl + "?id=" + oid,
                                                      callback,
                                                      null);

    }

    function loadThumb(thumb) {
        if (YAHOO.util.Dom.hasClass(thumb, 'no_images')) {
            return;
        }
        var oid = oidFromContextId(thumb);
        
        var callback = {
            success: function (o) {
                cachedResponseText[o.argument.oid] = o.responseText;
                var snippet = document.createElement('div');
                snippet.innerHTML = o.responseText;
                var images = snippet.getElementsByTagName('img');
                for (var i = 0; i < images.length; i++) {
                    var img = new Image();
                    img.src = images[i].src;
                    preloadedImages.push(img);
                }
                //               alert("num images preloaded: " + preloadedImages.length);
            },
            failure: function(o) {
                YAHOO.log("Error preloading tooltip for context with oid " + o.argument.oid);
            },
            argument: { oid: oid }
        };
        sendAjaxRequest(oid, {}, {}, callback);
    }

    return {
    init: function () {
            e.onContentReady('abstract_container', initTooltips, 'abstract_container');
        },
    preload: function () {
            if (!thumbs) {
                thumbs = YAHOO.util.Dom.getElementsByClassName('thumbnail', 'td');
            }
            for (var i = 0; i < 2 && i < thumbs.length; i++) {
                loadThumb(thumbs[i]);
            }
        }
    }

}();

tooltipGrid.init();
//tooltipGrid.preload();

function mouseInElement(e, el)
{
//    var el = document.getElementById(elName);
    if (!el) return false;
    
    var x = YAHOO.util.Event.getPageX(e);
    
    if (x < YAHOO.util.Dom.getX(el)) return false;
    if (x > YAHOO.util.Dom.getX(el)+el.offsetWidth) return false;
    
    var y = YAHOO.util.Event.getPageY(e);
    
    if (y < YAHOO.util.Dom.getY(el)) return false;
    if (y > YAHOO.util.Dom.getY(el)+el.offsetHeight) return false;
    
    return true;
}
