var w3c = false;
var ie = false;
var timerID = null; 
var timerOn = false; 

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 = BL();
    // Check if container exists first
    if($('pCsr') != null) {
        if(!ie) {
            $('pCsr').observe('mousemove',function(evt){tooltip.globalEvent = evt;});
        }
        $('pCsr').observe('mouseover', function(event){
            $$('#pCsr 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 BL(){
    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);
			}
        },



        /**
        * 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
    $('PU').clonePosition(obj,{setHeight:false, setWidth:false, offsetLeft:offL, offsetTop:offT});
    $('popupContent').update(newObject);
    if(Prototype.Browser.IE){
        $('PU').show();
    }
	else{
        $('PU').hide();
        $('PU').appear({duration:0.2});
    }
    if(slideshow){
        $('popupContent').insert('<a href="javascript:slideshow.open(\''+id+'\');" class="zoom" title="Slideshow">&nbsp;</a>');
    }
    $('PU').down('div.cartContainer').removeClassName('moreInfo');
    // Add events to Buy online button (if it exists) and Save to list link
  
    // Find compare container and show it
    var compareCont = $('PU').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 pCsr and each td
function addProductEvts(){
    if($('PU') != null) {
        // Add event listener to the div "pCsr". If user goes out of the product listing area then hide the PU
		// for compare view the container will be 'compare'
		var container = 'pCsr';
		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 "pCsr" 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){
                $('PU').hide();
            }
        });
        // Add event listener to every td to display the PU
        $$('#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 "PU"
						myAncestors.each(function(tag){
							if(tag.id == 'PU'){
							//alert(tag.id);
								inside = true;
							}
						});
						// If inside is false, then we have left the area...so hide the popup
						if(inside == false){
							$('PU').hide();
						}				
				
					});         
				//}
			});
			$('PU').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 "PU"
				myAncestors.each(function(tag){
					if(tag.id == 'PU'){
					//alert(tag.id);
						inside = true;
					}
				});
				// If inside is false, then we have left the area...so hide the popup
				if(inside == false){
					$('PU').hide();
				}
			});	
		}		
    } 
}


// 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;
}

