//  Tooltip script which pops up a layer with content when an object is hovered and also follows the mouse
//  The script is using objects and methods in the prototype and scriptacolous library, so these need to be included before this script.
//  Creator: Jake (jbnn) && Sigge (sfid)
//  Date: 090107 - 090204

var tooltip;
var globalProdId;

/**
 * Add event observer to check all a-tags for the rel attribute, 
 * which holds the link to the Big img.
 */
Event.observe(window, 'load', function() {
    var tipId = 'bigImg';
    var tipDelay;
    var tipTimeout = 20;     // Fix  to get correct positioning on first mouseover
    tooltip = IkeaPopup();
        
    // Check if container exists first
    if($('productsContainer') != null) {
        if(!ie) {
            $('productsContainer').observe('mousemove',function(evt){tooltip.globalEvent = evt;});
        }
        $('productsContainer').observe('mouseover', function(event){
            $$('a[rel]').each(function(element) {
                var prodId = element.down('img').readAttribute('id');

                $(prodId).observe('mouseover', function(event){
                    globalProdId = prodId;
                    clearTimeout(tipDelay);
                    // Change timeout to correct value when div created
                    if($(tipId) != null){
                        tipTimeout = 400;
                    }
                    tipDelay = setTimeout(function(){tooltip.createToolTip(element.rel,254,254,$(prodId),tipId)},tipTimeout);
                    // This is for IE6. If there are select dropdowns these need to be hidden, else they will render through this popup layer
                    tagVisibility('SELECT','hide');
                });

                $(prodId).observe('mouseout', function(event){
                    clearTimeout(tipDelay);
                    tooltip.hide();
                    tagVisibility('SELECT','show');
                });
            });
        });
    }
});

/**
* Object for common IKEA JS popup and tooltip handling
*/
function IkeaPopup(){
    var cssClass = 'tt';
    var top = 5;    // tooltip offset top
    var left = 1;   // tooltip offset left
    var tt,divCont,h;
    var ie = document.all ? true : false;
    var contentHolderId;
    var globalEvent;
    
    return{
    	/**
    	* Creates a JS popup layer to be populated with content
    	* 
    	* @param _width		The width in pixels for the popup
    	* @param _height	          The height in pixels for the popup
    	* @param _id		          The ID that will be given to the div that holds the content of the popup
    	* @param _ownerObj	          The prototype DOM element that the popup will align to
         * @param _offsetX	          The x position of the popup related to the _ownerObj
         * @param _offsetY	          The y position of the popup related to the _ownerObj
    	* @return			 Nothing
    	*/
        createGenericPopup:function(_width,_height,_id,_class,_ownerObj,_offsetX,_offsetY){
            if(tt == null){
                contentHolderId = _id;
                tt = new Element('div', {'id': _id, 'class': _class});
                document.body.insert(tt);
            }
            
            tt.setOpacity(0);
     		tt.show();
            tt.style.height = _height ? _height + 'px' : 'auto';            
            tt.style.width = _width ? _width + 'px' : 'auto';

            pos = _ownerObj.cumulativeOffset();
            tt.style.top = pos.top + _offsetY + 'px';
			tt.style.left = pos.left + _offsetX + 'px';
            
            new Effect.Opacity(tt,{
                from: 0.0,
                to: 1.0,
                duration: 0.4
            });
        },


    	/**
    	* Creates a JS tooltip that follows the mousepointer
    	* 
    	* @param width		The width in pixels for the tooltip
    	* @param height		The height in pixels for the tooltip
    	* @param objId		The prototype DOM element that the tooltip will align to
    	* @param ttId		The ID that will be given to the div that holds the content of the tooltip
    	* @return			Nothing
    	*/
        createToolTip:function(content,width,height,objId,ttId){
            var img, shadowR, shadowB;
            if(tt == null){
                tt = new Element('div', {'id': ttId, 'class': cssClass});
                img = new Element('img', {'id': 'bigViewImg' ,'class': 'bigView'});
                tt.insert(img);
                shadowR = new Element('img', {'class': 'shadowR', 'src': '/ms/img/tt_shadow_right.gif'});
                tt.insert(shadowR);
                shadowB = new Element('img', {'class': 'shadowB', 'src': '/ms/img/tt_shadow_bottom.gif'});
                tt.insert(shadowB);
                document.body.insert(tt);
            }
            //objId.onmousemove = this.pos;
            objId.observe('mousemove', this.pos);
            tt.setOpacity(0);
            
            $('bigViewImg').replace('<img src="' + content +'" id="bigViewImg" class="bigView" />');

            tt.show();
            tt.style.width = width ? width + 'px' : 'auto';
            if(!width && ie){
                tt.style.width = tt.offsetWidth;
            }
            h = parseInt(tt.offsetHeight) + top;
            
            new Effect.Opacity(tt,{
                from: 0.0,
                to: 1.0,
                duration: 0.4
            });
            if(!ie) setTimeout("tooltip.refreshPos();",10);
        },

        /**
        * Aligns the popup to a given Prototype DOM element
        *
        * @param objId		The Prototype DOM element that the popup will align with
    	* @return			Nothing
        */
        alignToObject:function(objId){
            var pos, left, top;

            // Get the position of the specified obj
            pos = objId.cumulativeOffset();
            left = pos.left;
            top = pos.top;
            // Set position
            layerHeight = tt.getHeight();
            top = top - layerHeight - 5;
            left = left - 32;
            
            // Move the layer 
            tt.style.top = top + 'px';
            tt.style.left = left + 'px';
            
            tt.show();
        },

        
        /**
        * Helper function to createToolTip
        *
        * @param e			Event object
    	* @return			Nothing
        */
        pos:function(e){
            var u = ie ? window.event.clientY + document.documentElement.scrollTop : e.pageY;      // Get y-position of mouse
            var l = ie ? window.event.clientX + document.documentElement.scrollLeft : e.pageX;     // Get x-position of mouse
            var winW = document.viewport.getWidth();    // Get the window width
            var w = tt.getWidth();           // Get the width of the tip

            var prodIdTop = $(globalProdId).viewportOffset().top;
            
            // Make sure the tip wont end up outside the viewport
            if((l + w) > winW){
                tt.style.left = (l - w) + 'px';
            }else{
                tt.style.left = (l + left) + 'px';
            }
            if((prodIdTop) < (h -50)){
                // Move layer below mouse
                tt.style.top = (u + 25) + 'px';
            }else{
                // Position layer above mouse
                tt.style.top = (u - h) + 'px';
            }
            
            //$('trace').update('this: ' + this.id + '<br/> top:' + u + '<br/> left:' + l + '<br/> prodIdTop:' + prodIdTop);
        },
        
        refreshPos:function() {
            tooltip.pos(tooltip.globalEvent);
        },

        /**
        * Updates the content in the popup
        *
        * @param layoutString	A string with a valid HTML snippet
        * @return				Nothing
        */
		
		setGenericContent:function(layoutString) {
			tt.update(layoutString);
		},
		
		/**
	* Returns a prototype object that holds the content of the popup
	*
    	* @return		A prototype object that holds the content of the popup
	*/
		getContent:function() {
			return tt;
		},

		/**
	* Generates a layout with a spinning circle. Handy when loading ajax.
	*/
		generateLoadingLayout:function()
		{
			var retString = "<div style=\"text-align:left;\"><img src=\"/ms/img/loading.gif\" width=\"32\" height=\"32\" /></div>";
			return retString;
		},


		/**
		 * Makes the popup show the layout that informs the user that a remote call is loading.
		 * Requires that a method called generateLoadingLayout that returns valid HTML layout is defined.
		 * @return					false to stop link exection
		 */
		loadingPopup:function() {
			this.setGenericContent(this.generateLoadingLayout());
			var picDiv = tt.firstDescendant();
			picDiv.style.position = "relative";
			picDiv.style.left = ((parseInt(tt.getWidth()) / 2) - 16)+"px";
			picDiv.style.top = ((parseInt(tt.getHeight()) / 2) - 16)+"px";
			return false;
		},


		/**
	* Hides the popup
	*
    	* @return			Nothing
		*/
        hide:function(){
            if(tt){
                tt.hide();
            }
        }
    };
};