/*Change History
-------------------------------------------------------------------------
Task ID       : #203-sale
Date          : 2010/06/14
Developer     : Manish Sain (IRIS)
Description   : TrackedSale sale redirection set
Changes In    : triggerOnClick
-------------------------------------------------------------------------*/

Site.Widgets.Tooltip = Class.create
(
    Site.Base,
    {
        initialize: function($super, tooltip, trigger, options) {
            $super();

            this.setOptions
            (
                options,
                {
                    anchor: "left",
                    showOnClick: false,
                    durationShow: 0,
                    delayShow: 0.2,
                    delayHide: 0.2,
                    tooltipClassName: "tooltip",
                    ignoreClick: true,
                    triggerActiveClassName: "active",
                    origin: "element", /* choose "mouse" to have the tooltip show where the mouse is instead */
                    offsetY: 0,
                    offsetX: 0,
                    triggerSelector: "a",
                    nubWidth: 30,
                    nubIndent: 12,
                    width: 353, /* most tooltips are this width */
                    cancelTrigger: false,
                    ajaxEnabled: false
                }
            );

            this.addObservers("triggerOnClick", "ignoreClick", "triggerOnMouseOver", "triggerOnMouseOut", "btCloseOnClick", "tooltipOnMouseOver", "tooltipOnMouseOut");
            this.addBlocks("hide", "show", "runAjax", "scrollCheck");

            this.tooltip = tooltip;

            this.nub = this.tooltip.select("div.cap-tp div").first();

            this.width = this.options.width || this.tooltip.getWidth(); // should the width - Safari can't calculate it properly for some reason :(

            this.height = this.tooltip.getHeight();

            this.trigger = trigger;

            this._setup();
        },

        triggerOnClick: function(event) {
            if (this.cancelTrigger) {
                return;
            }
            var element = Event.element(event);

            this._setPosition(event);

            if (this.tooltip.visible()) {
                this.hide();
            }
            else {
                //TaskID #203-Sale
                if (element.innerHTML.indexOf("Tracked Lot") == -1 && element.innerHTML.indexOf("Tracked Sale") == -1) {
                    if (this.options.ajaxEnabled) {
                        this.runAjax();
                    }
                    else {
                        this.show();
                    }
                }
                else {
                    this.hide();
                    trackedLotsPath = "/MyChristies/my_tracked_lots_bids.aspx";
                    if (element.innerHTML.indexOf("Tracked Sale") > -1) {
                        trackedLotsPath = "/MyChristies/my_auction_calendar.aspx";
                    }
                    if (securerootpath) trackedLotsPath = securerootpath + trackedLotsPath;
                    document.location = trackedLotsPath;
                }
            }

            if (element.blur)
                element.blur();


            if (this.options.onTriggerClick)
                this.options.onTriggerClick(this.trigger);

            Event.stop(event);


            element = null;
        },


        tooltipOnMouseOver: function(event) {
            // must cancel any hide timeouts, in case the tooltip itself has forced a mouse out
            if (this.hideTimeout)
                window.clearTimeout(this.hideTimeout);

        },

        tooltipOnMouseOut: function(event) {
            // mousing out of the tooltip should also hide it, if the activation is not via a click

            if (!this.options.showOnClick)
                this.hideTimeout = window.setTimeout(this.blocks.hide, this.options.delayHide * 1000);

        },

        triggerOnMouseOver: function(event) {
            this._setPosition(event);

            if (this.hideTimeout)
                window.clearTimeout(this.hideTimeout);

            this.showTimeout = window.setTimeout(this.blocks.show, this.options.delayShow * 1000);

            Event.stop(event);
        },

        triggerOnMouseOut: function(event) {
            // clear any show timeouts so that the tooltip doesn't show when rolling the mouse across 
            if (this.showTimeout) {
                window.clearTimeout(this.showTimeout);
            }

            this.hideTimeout = window.setTimeout(this.blocks.hide, this.options.delayHide * 1000);

        },

        ignoreClick: function(event) {
            Event.stop(event);

        },

        setDefaultAnchor: function() {
            if (this.options.anchor == "left")
                this._anchorLeft();
            else
                this._anchorRight();
        },

        _setup: function() {
            this.setDefaultAnchor();

            this.btClose = this.tooltip.select("div.bt-close").first();

            if (this.btClose) {
                if (this.options.showOnClick) {
                    addEvent(this.btClose, "click", this.observers.btCloseOnClick);
                }
                else {
                    this.btClose.hide();
                }
            }

            addEvent(this.tooltip, "mouseover", this.observers.tooltipOnMouseOver);
            addEvent(this.tooltip, "mouseout", this.observers.tooltipOnMouseOut);

            if (this.options.showOnClick) {
                addEvent(this.trigger, "click", this.observers.triggerOnClick);
            }
            else {
                if (this.options.ignoreClick)
                    addEvent(this.trigger, "click", this.observers.ignoreClick);

                addEvent(this.trigger, "mouseover", this.observers.triggerOnMouseOver);
                addEvent(this.trigger, "mouseout", this.observers.triggerOnMouseOut);
            }

        },

        btCloseOnClick: function(event) {
            this.hide();
        },

        _anchorLeft: function() {
            this.offsetX = -this.options.nubIndent;

            if (this.nub) {
                this.nub.style.left = this.options.nubIndent + 'px';
            }
        },

        _anchorRight: function() {
            this.offsetX = -(this.width - 40);

            if (this.nub) {
                this.nub.style.left = (this.width - this.options.nubWidth - this.options.nubIndent) + 'px';
            }
        },

        _setPosition: function(event) {
            var element = Event.element(event);

            var x;
            var y;

            if (this.options.getElementOffset) {
                offset = this.options.getElementOffset();
                x = offset[0]
                y = offset[1];

                // set the nub to the left
            }
            else {
                if (this.options.origin == "element") {
                    var offset;
                    offset = element.cumulativeOffset();

                    x = offset[0]
                    y = offset[1] + element.offsetHeight;
                }
                else {
                    x = Event.pointerX(event);
                    y = Event.pointerY(event);
                }

                // now switch the anchor if the popup is outside the window
                // note that we don't do this if the consumer has provided a callback 

                var offset = element.cumulativeOffset();

                //alert(this.options.anchor + "," + offset[0] + "," + this.width + "," + document.viewport.getWidth());

                this.setDefaultAnchor();

                if (offset[0] + this.width > document.viewport.getWidth()) {
                    this._anchorRight();
                }
                else if (offset[0] - this.width < 0) {
                    this._anchorLeft();
                }

            }
            //Bit of code for triggers sharing one tooltip populated by ajax
            //if the trigger is active we close the tooltip, otherwise we move the tooltip to the new trigger rather than closing it
            if (this.options.ajaxEnabled) {
                var ttoffset;
                ttoffset = this.tooltip.cumulativeOffset();
                if ((x == (this.options.nubIndent + ttoffset[0])) && (y == ttoffset[1]) && (this.tooltip.visible())) {
                    this.tooltip.setStyle({ left: "0px", top: "0px", display: "block" });
                }
                else {
                    this.hide();
                    this.tooltip.setStyle({ "left": (x + this.offsetX + this.options.offsetX) + "px", "top": (y + this.options.offsetY) + "px" });
                }
            }
            else {
                this.tooltip.setStyle({ "left": (x + this.offsetX + this.options.offsetX) + "px", "top": (y + this.options.offsetY) + "px" });
            }

        },

        runAjax: function() {
            //Ajax Tooltips//
            //Functionality to load contents of a shared tooltip via ajax//
            //All ajax populated tooltip triggers should share the same tooltip//
            //Ajax call is passed via the href, returns html contents of div.body//
            //Added by Stephen Dettling, March 31, 2010//

            //clear contents and show loading
            var tooltipBody = this.tooltip.select('div.body');
            tooltipBody[0].update("<img src='/images/widgets_tooltip/bg_ajax_loading.gif' />");
            this.tooltip.addClassName("ttajaxload");
            this.show();
            //here we do ajax
            var hrefParts = this.trigger.href.split("#");
            var url = hrefParts[hrefParts.length - 1];
            //alert(url);
            var thisLocal = this;
            new Ajax.Request(
				url,
				{
				    method: 'get',
				    onSuccess: function(transport) {
				        this.tooltip.removeClassName("ttajaxload");
				        var response = transport.responseText;
				        if (response != "") {
				            tooltipBody[0].update(response);
				            thisLocal.scrollCheck();
				        }
				        else {
				            tooltipBody[0].update("There was a problem loading this content, try again later.");
				        }
				    },
				    onFailure: function() {
				        this.tooltip.removeClassName("ttajaxload");
				        tooltipBody[0].update("There was a problem loading this content, try again later.");
				    }
				});
        },

        show: function() {
            if (this.options.beforeShow)
                this.options.beforeShow(this.trigger);

            if (this.showTimeout)
                window.clearTimeout(this.showTimeout);

            if (this.options.durationShow > 0) {
                var effect = new Effect.Appear(this.tooltip, { duration: this.options.durationShow });
                effect = null;
            }
            else {
                this.tooltip.show();
            }
            if (!this.options.ajaxEnabled) {
                this.scrollCheck();
            }
            this.trigger.addClassName(this.options.triggerActiveClassName);
        },

        hide: function() {
            if (this.options.beforeHide)
                this.options.beforeHide(this.trigger);

            if (this.hideTimeout)
                window.clearTimeout(this.hideTimeout);

            this.tooltip.hide();

            this.trigger.removeClassName(this.options.triggerActiveClassName);
        },

        scrollCheck: function() {
            //Scroll Outside//
            //Functionality to scroll the window if the tooltip falls outside of the viewport//
            //Added by Stephen Dettling, March 4, 2010//
            //alert('show')
            var ttoffset = this.tooltip.cumulativeOffset();
            var scrolloffset = document.viewport.getScrollOffsets();
            var tooltipOffset = ttoffset[1];
            var triggerPos = this.trigger.cumulativeOffset();
            var pixelstobottom = (Number(tooltipOffset) + Number(this.tooltip.getHeight()));
            var pixelstowinbot = (Number(document.viewport.getHeight()) + Number(scrolloffset[1]));

            //if the bottom of the tooltip is greater thant the bottom of the viewport
            if (pixelstobottom > pixelstowinbot) {
                //number of pixels the tooltip extends below the viewport
                var newScroll = (pixelstobottom - pixelstowinbot);

                //number of pixels from the top of the viewport to the top of the trigger element
                var triggerOffset = Number(scrolloffset[1]) - Number(triggerPos[1]);

                //the offset relative to the trigger element that the window needs to scroll to show the whole tooltip
                var finalOffset = triggerOffset + newScroll;

                //scriptaculous scrollto effect scrolls to the element trigger with the offset calculated above
                Effect.ScrollTo(this.trigger, { offset: finalOffset, duration: .25 });
            }

            //End Scroll Outside//
        },

        destroy: function() {
            if (this.btClose) {
                removeEvent(this.btClose, "click", this.observers.btCloseOnClick);
            }

            removeEvent(this.tooltip, "mouseover", this.observers.tooltipOnMouseOver);
            removeEvent(this.tooltip, "mouseout", this.observers.tooltipOnMouseOut);

            if (this.options.showOnClick) {
                removeEvent(this.trigger, "click", this.observers.triggerOnClick);
            }
            else {
                removeEvent(this.trigger, "mouseover", this.observers.triggerOnMouseOver);
                removeEvent(this.trigger, "mouseout", this.observers.triggerOnMouseOut);
            }

            this.hideTimeout = null;
        }
    }

);