//  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
    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 + ' shadow-one' });
                conA = new Element('div', {'class': 'corner-a'});
                tt.insert(conA);
				conB = new Element('div', {'class': 'corner-b'});
                tt.insert(conB);
				
                shadow2 = new Element('div', {'class': 'shadow-two'});
                tt.insert(shadow2);
				shadow3 = new Element('div', {'class': 'shadow-three'});
                shadow2.insert(shadow3);
				shadow4 = new Element('div', {'class': 'shadow-four'});
                shadow3.insert(shadow4);                
                document.body.insert(tt);
            }
            tt.setOpacity(0);
            tt.show();
            tt.style.height = _height ? _height + 'px' : 'auto';            
            tt.style.width = _width ? _width + 'px' : 'auto';
            tt.style.border='none';
            pos = _ownerObj.cumulativeOffset();
            tt.style.top = pos.top + _offsetY + 'px';
            tt.style.left = pos.left + _offsetX + 'px';
            if(!ie){
				new Effect.Opacity(tt,{
					from: 0.0,
					to: 1.0,
					duration: 0.4
				});
			}else{
				tt.setOpacity(1);
			}
        },

createGenericPopupNew: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 + ' shadow-one' });
                conA = new Element('div', {'class': 'corner-a'});
                tt.insert(conA);
				conB = new Element('div', {'class': 'corner-b'});
                tt.insert(conB);
				
                shadow2 = new Element('div', {'class': 'shadow-two'});
                tt.insert(shadow2);
				shadow3 = new Element('div', {'class': 'shadow-three'});
                shadow2.insert(shadow3);
				shadow4 = new Element('div', {'class': 'shadow-four'});
                shadow3.insert(shadow4);                
                document.body.insert(tt);
            }
		_ownerObj.observe('mousemove', this.pos);
            tt.setOpacity(0);
            tt.show();
			 h = parseInt(tt.offsetHeight) + top;
            tt.style.height = _height ? _height + 'px' : 'auto';            
            tt.style.width = _width ? _width + 'px' : 'auto';
            tt.style.border='none';
            pos = _ownerObj.cumulativeOffset();
				
			
             if(!ie && Prototype.Browser.WebKit){
				new Effect.Opacity(tt,{
					from: 0.0,
					to: 1.0,
					duration: 0.4
				});
			}else{
				tt.setOpacity(1);
			}
        },
	 /**
     * 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
			
				
			
            if((l + w) > winW){
                tt.style.left = (l - w) + 'px';
            }
			else{
                tt.style.left = (l + left) + 'px';
            }
		if($(this).tagName =="A")
			{
			 var prodIdTop = $(this).viewportOffset().top;
				if (navigator.platform.toLowerCase().indexOf('mac') != -1) 
				 {
						if(Prototype.Browser.Gecko)
						{
							tt.style.top = (u +12) + 'px';
							tt.style.left=(l-6) + 'px';
						} else if(Prototype.Browser.WebKit)
						{
							tt.style.top = (u +10) + 'px';
							tt.style.left=(l-7) + 'px';
						}
				 } 		
				else {
					if(Prototype.Browser.IE)
						{
						tt.style.top = (u +15) + 'px';
						tt.style.left=(l-8)+'px';
						}
					else {
						tt.style.top = (u +17) + 'px';
						tt.style.left=(l-5)+'px';
						}
					}
			 }
			else{
			var prodIdTop = $(globalProdId).viewportOffset().top;
            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('.shadow-four').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\" /></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 id = obj.down('.productPadding a').readAttribute('href').split('/').last();
    var offL = setProductOffset(obj).left;
    var offT = setProductOffset(obj).top;
	
    var slideshow = typeof(js_fn_SLIDE_SHOW_ENABLED) != "undefined" ? js_fn_SLIDE_SHOW_ENABLED : false;
    
    // Remove noscript tags
    var noscript = newObject.select('noscript');
    noscript.each(function(tag){tag.remove()});
    
    // 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});
    }
    if(slideshow){
        $('popupContent').insert('<a href="javascript:slideshow.open(\''+id+'\');" class="zoom" title="Slideshow">&nbsp;</a>');
    }
    $('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');
	if (typeof compareCont != 'undefined') {
    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
		// for compare view the container will be 'compare'
		var container = 'productsContainer';
		if($('compare') != null){
			container = 'compare';
		}
        $(container).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" or "compare"
            myAncestors.each(function(tag){
                if(tag.id == container){
                    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.hasClassName('noBorder') && !td.hasClassName('features'))
			 || (td.hasClassName('width2column') || td.hasClassName('width3column') || td.hasClassName('width4column'))){
                if (typeof td.down('div.popupListener') != 'undefined') {
					var popupId = td.down('div.popupListener').readAttribute('id');
					$(popupId).observe('mouseover', function(e){
						prodInfoDelay = setTimeout(function(){showProdInfo(td)},250);										
					});
					$(popupId).observe('mouseout', function(e){			     
						clearTimeout(prodInfoDelay);
					});         				
				} else {
					td.observe('mouseover', function(e){
						prodInfoDelay = setTimeout(function(){showProdInfo(td)},250);
					});
					td.observe('mouseout', function(e){
						clearTimeout(prodInfoDelay);
					});
				}
            }
        });
		
		// more listeners for compare view
		if($('compare') != null){
			$$('#productsTable td').each(function(td) { 
				 //if(td.hasClassName('width2column') || td.hasClassName('width3column') || td.hasClassName('width4column') ){
					td.observe('mouseover', function(e){	
						var element = Event.element(e);
						var inside = false;
						//alert('mouse out');
						// 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 "productPopup"
						myAncestors.each(function(tag){
							if(tag.id == 'productPopup'){
							//alert(tag.id);
								inside = true;
							}
						});
						// If inside is false, then we have left the area...so hide the popup
						if(inside == false){
							$('productPopup').hide();
						}				
				
					});         
				//}
			});
			$('productPopup').observe('mouseout',function(e) {
				var element = Event.element(e);
				var inside = false;
				//alert('mouse out');
				// 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 "productPopup"
				myAncestors.each(function(tag){
					if(tag.id == 'productPopup'){
					//alert(tag.id);
						inside = true;
					}
				});
				// If inside is false, then we have left the area...so hide the popup
				if(inside == false){
					$('productPopup').hide();
				}
			});	
		}		
    } 
}

// Remove all event listeners for the productPopup
function removeProductEvts(){    
	$$('#productsTable td').each(function(td) { 
		if((!td.hasClassName('productDivider') && !td.hasClassName('compareContainer') && !td.hasClassName('noBorder') && !td.hasClassName('features'))
		 || (td.hasClassName('width2column') || td.hasClassName('width3column') || td.hasClassName('width4column'))){
			if (typeof td.down('div.popupListener') != 'undefined') {
				var popupId = td.down('div.popupListener').readAttribute('id');		
				$(popupId).stopObserving('mouseover');
			} else {
				td.stopObserving('mouseover');
			}				
		}
	});
	if($('compare') == null) {
		$('productsContainer').stopObserving('mouseout');
	} else {		
		$('compare').stopObserving('mouseout');
		$('productPopup').stopObserving('mouseout');
		$$('#productsTable td').each(function(td) { 			
			td.stopObserving('mouseover'); 			
		});
	}
}

// Pixel fix to open all popups in correct offset
function setProductOffset(obj){
    var objOffset = new Object();
    var offL = -5;
    var offT = -10;
	if($('compare') != null) {
		offL = -4;
		offT = -9;
	}
	var elem = obj.parentNode.childNodes.length;
    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){            
			if($('compare') == null) {
				offL = -4;
				offT = -10;
				if(myPos == 1){offL = -5;}
			} else {
				offL = -4;
				offT = -9;
				if(elem==3){
					if(myPos == 1){offL = -4;}
					else if(myPos % 2 == 0){offL = -2;}
					else if(myPos % 2 != 0){offL = -3;}
				}
			}
        }
		else if(Prototype.Browser.Gecko){
			if($('compare') == null) {
				if(myPos == 5){offL = -4;}
			} else {
				if(myPos % 2 == 0){offL = -3;}
			}
        }
		else if(Prototype.Browser.WebKit){
            offL = -4;
            offT = -9;
            if(myPos == 1){offL = -5;}
        }
    }
    objOffset.left = offL;
    objOffset.top = offT;
    return objOffset;
}
