//  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;
var ie = document.all ? true : false; // mater
var prodInfoDelay;

/**
 * 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
    var prodInfoDelay;
    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){
            $$('#productsContainer 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,'','',$(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');
                });
            });
        });
    }
    
    addProductEvts();
});

/**
* 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,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){
            var col1, col2, ttCont;
            if(tt == null){
                contentHolderId = _id;
                tt = new Element('div', {'id': _id, 'class': _class});
                    col1 = new Element('div', {'class': 'offset color1'});
                    tt.insert(col1);
                        col2 = new Element('div', {'class': 'offset color2'});
                        col1.insert(col2);
                            ttCont = new Element('div', {'class': 'offset ttContainer'});
                            col2.insert(ttCont);
                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, imgAttr, col1, col2, ttCont, prodInfoCont;
            if(tt == null){
                tt = new Element('div', {'id': ttId, 'class': cssClass});
                    col1 = new Element('div', {'class': 'offset color1'});
                    tt.insert(col1);
                        col2 = new Element('div', {'class': 'offset color2'});
                        col1.insert(col2);
                            ttCont = new Element('div', {'class': 'offset ttContainer'});
                            col2.insert(ttCont);
                                img = new Element('img', {'id': 'bigViewImg' ,'class': 'bigView'});
                                ttCont.insert(img);
                                imgAttr = new Element('div', {'id': 'bigImgAttributes'});
                                ttCont.insert(imgAttr);

                document.body.insert(tt);
            }

            objId.observe('mousemove', this.pos);
            tt.setOpacity(0);
            
            // Update content in tooltip
            $('bigViewImg').replace('<img src="' + content +'" id="bigViewImg" class="bigView" />');
            try {
                prodInfoCont = objId.up('.colProduct').down('.prodInfoContainer').adjacent('.prodInfo');
                $('bigImgAttributes').update();
                prodInfoCont.each(function(element){
                    $('bigImgAttributes').insert(element.cloneNode(true));
                });
            }catch(e){
                $('bigImgAttributes').setStyle({ margin: '0', padding: '0' });
            };

            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.down('.ttContainer').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 class=\"content\" style=\"text-align:center;\"><div class=\"headline\" style=\"text-align:left;\">Loading ...</div><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.down('.ttContainer');
			// 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();
            }
        }
    };
};


/**
 * Creator: JBNN
 * Date: 091216
 * New functions for creating a popup div in the product listing on mouseover
 */
function showProdInfo(obj){
    var newObject = obj.down().cloneNode(true);
    var offL = setProductOffset(obj).left;
    var offT = setProductOffset(obj).top + 6;
    
    // Initiate the popup
    $('productPopup').clonePosition(obj,{setHeight:false, setWidth:false, offsetLeft:offL, offsetTop:offT});
    $('popupContent').update(newObject);
    if(Prototype.Browser.IE){
        $('productPopup').show();
    }else{
        $('productPopup').hide();
        $('productPopup').appear({duration:0.2});
    }
    $('productPopup').down('div.cartContainer').removeClassName('moreInfo');
    
    // Add events to Buy online button (if it exists) and Save to list link
    /*
    var buyOnlineBtn = $('productPopup').down('div.buttonContainer .button');
    if (typeof buyOnlineBtn != 'undefined') {
        $(buyOnlineBtn).observe('click', function(){
            removeProductEvts();
        });
    }
    var saveToListLnk = $('productPopup').down('div.buttonsContainer .listLink');
    $(saveToListLnk).observe('click', function(){
       removeProductEvts();
    });
    */

    /*
    // Find compare container and show it
    var compareCont = $('productPopup').down('div.compare');
    compareCont.style.display = 'block';
    // Find chk in container
    var cb = compareCont.down('input');
    // Force a (re)check (for IE of course)
    var objCb = obj.down('div.cartContainer .compare').down('input');
    if (objCb.checked){cb.checked = 'checked'};
  
    //Add click observer to the checkbox in popup that will copy values to the original objects in the product listing
    Event.observe(cb,'click',function(e) {
        var element = Event.element(e);
        var chkValue = element.checked;
        
        var objCb = obj.down('div.cartContainer .compare').down('input');
        var compareCont = $('display_'+objCb.id).up('div.compare');    //Get the div with the chk for display
        
        objCb.checked = chkValue;
        var cbDisplay = compareCont.down('input');
        cbDisplay.checked = chkValue;
        
        cbDisplay.stopObserving('click');
        cbDisplay.observe('click',function(e) {
            objCb.checked = this.checked;
            if(!objCb.checked){compareCont.hide()}
            updateCheckbox(objCb,false);   //Set cookie in compare.js
        });
        
        if(chkValue){
            compareCont.style.display = 'block';
        }else{
            compareCont.style.display = 'none';
        }
        updateCheckbox(objCb,false);   //Set cookie in compare.js
    });	
    */
}

  
// Add event listeners to the productsContainer and each td
function addProductEvts(){
    if($('productPopup') != null) {
        // Add event listener to the div "productsContainer". If user goes out of the product listing area then hide the productPopup
        $('productsContainer').observe('mouseout', function(e){
            var element = Event.element(e);
            var inside = false;

            // Get the element we mouse out to
            var goToElement = (e.relatedTarget) ? e.relatedTarget : e.toElement;
            if(goToElement == null){return};
            myAncestors = goToElement.ancestors();
     
            // Traverses the parents of the related target (the element that the mouse goes to) and try to find the "productsContainer"
            myAncestors.each(function(tag){
                if(tag.id == 'productsContainer'){
                    inside = true;
                }
            });
            
            // If inside is false, then we have left the area...so hide the popup
            if(inside == false){
                $('productPopup').hide();
            }
        });
        
        // Add event listener to every td to display the productPopup
        $$('#productsTable td').each(function(td) { 
            if(!td.hasClassName('productDivider') && !td.hasClassName('compareContainer')){
                td.observe('mouseover', function(e){
                    prodInfoDelay = setTimeout(function(){showProdInfo(td)},25);
                });
            }
        });

        $$('#productsTable td').each(function(td) { 
            if(!td.hasClassName('productDivider') && !td.hasClassName('compareContainer')){
                td.observe('mouseout', function(e){
                    clearTimeout(prodInfoDelay);
                });
            }
        });
    }
}

// Remove all event listeners for the productPopup
function removeProductEvts(){
    $$('#productsTable td').each(function(td) { 
        if(!td.hasClassName('productDivider') && !td.hasClassName('compareContainer')){
            td.stopObserving('mouseover')
        }
    });
    
    $('productsContainer').stopObserving('mouseout');
}

// Pixel fix to open all popups in correct offset
function setProductOffset(obj){
    var objOffset = new Object();
    var offL = -5;
    var offT = -10;
    var prevCols = obj.previousSiblings().length;
    var myPos = prevCols + 1;
    
    if (navigator.platform.toLowerCase().indexOf('mac') != -1) {
        if(Prototype.Browser.Gecko){
            if(myPos == 5){offL = -4;}
        }else if(Prototype.Browser.WebKit){
            offL = -4;
            offT = -9;
            if(myPos == 1){offL = -5;}
        }
    }else{
        if(Prototype.Browser.IE){
            offL = -4;
            offT = -10;
            if(myPos == 1){offL = -5;}
        }else if(Prototype.Browser.Gecko){
            if(myPos == 2){offL = -6;}
        }else if(Prototype.Browser.WebKit){
            offL = -4;
            offT = -9;
            if(myPos == 1){offL = -5;}
        }
    }
    
    objOffset.left = offL;
    objOffset.top = offT;
    return objOffset;
}
