var productPreview = new Object();

// number that triggers productPreview.write
// lower number is more difficult to achieve
productPreview.nIntentSensitivity = 4;

// number of milliseconds until preview is shown
productPreview.nShowPreviewDelay = 450;

/**
* Initialize popup divs.
*/
productPreview.ini = function()
{
    if (!document.getElementById) return;
    var cDivs = document.getElementsByTagName('div');

    for (var i = 0; i < cDivs.length; i++)
	{
		var oDiv = cDivs[i];
		
		if ( oDiv.className == 'preview' )
		{
		    // find product link and attach events to it
			var oA = oDiv.getElementsByTagName('a')[0];

            oA.pImage = oDiv.getAttribute('popupImage');
            oA.pImageWidth = oDiv.getAttribute('popupImageWidth');
            oA.pImageHeight = oDiv.getAttribute('popupImageHeight');
            oA.pText = oDiv.getAttribute('popupText');
            oA.preview = null;
			oA.shield = null;

			oA.id = 'productPreview_ID_'+i;

			oA.onmouseover = productPreview.startShowTimers;
			oA.onmouseout  = productPreview.startHideTimers;
		}
	}
}

/**
* This function starts timers that create DOM elements and start the preview.
*/
productPreview.startShowTimers = function()
{
    // used to pass object into timer functions
	var oA = this;
	
	// kill hidePreviewTimer
	if ( oA.hidePreviewTimer )
	{
		clearTimeout(oA.hidePreviewTimer);
		oA.hidePreviewTimer = null;
	}
	
	if ( !oA.preview ) productPreview.writeDecision( oA );
	else if ( oA.preview.style.display == 'none' ) oA.showPreviewTimer = setTimeout( function(){ productPreview.show( oA ) }, productPreview.nShowPreviewDelay );
}

/**
* This function decides whether or not to write preview HTML. It
* captures/compares mouse position over time to determine if the user
* is "thinking" about a given product. If sensitivity threshold is
* reached, then write HTML into page.
*/
productPreview.writeDecision = function( oA )
{
    // This function gets the current mouse position
	function getMousePosition( e )
	{
		if (!e) var e = window.event;
		oA.currentMouseX = e.screenX;
		oA.currentMouseY = e.screenY;
	}

	// initialize previousMouse position
	// high number guarantees difference is greater than sensitivity threshold
	oA.previousMouseX = oA.previousMouseY = 10000;
	oA.onmousemove = getMousePosition;


	// This function compares mouse coordinates.
	function determineIntent()
	{
		// if the difference between previous and current coordinates (for both x and y) are less than the sensitivity threshold
		if ( (Math.abs(oA.previousMouseX-oA.currentMouseX)<productPreview.nIntentSensitivity) && (Math.abs(oA.previousMouseY-oA.currentMouseY)<productPreview.nIntentSensitivity) )
		{
			clearInterval(oA.determineIntentInterval);
			oA.determineIntentInterval = null;
			oA.onmousemove = null;
			
			// finally write the HTML
			productPreview.write( oA )
			
			// start showPreviewTimer // delay - 1 determineIntent interval
			oA.showPreviewTimer = setTimeout( function(){ productPreview.show( oA ) }, productPreview.nShowPreviewDelay - 100 );
		}
		oA.previousMouseX = oA.currentMouseX;
		oA.previousMouseY = oA.currentMouseY;
	}

	oA.determineIntentInterval = setInterval( determineIntent, 100 );
}

/**
* This function stops all timers and hides the preview.
*/
productPreview.write = function(oA) {
    var oPreviewBubble = document.createElement('div');
    oPreviewBubble.className = 'productPreview';
    document.body.appendChild(oPreviewBubble);

    oA.preview = oPreviewBubble;

    // used so preview can find associated oA
    oA.preview.oA_id = oA.id;

    // make sure there is no 'dead' space when user is moused over preview
    oA.preview.onmouseover = productPreview.startShowTimers;
    oA.preview.onmouseout = productPreview.startHideTimers;
    oA.preview.onclick = function() { document.location = oA.href };

    var addlOffset = 0;
    var imageShrinkPerc = 1;

    if (oA.pText) {
        // place product preview text
        var oPreviewText = document.createElement('div');
        oPreviewText.className = 'previewText';
        oPreviewText.innerHTML = oA.pText;
        oPreviewText.style.zIndex=1;
        oPreviewBubble.appendChild(oPreviewText);

        addlOffset = 30;
        imageShrinkPerc = .8;
    }
    //else {
    // get product preview image source
    var sSrc;
    if (oA.pImage) sSrc = oA.pImage;
    else {
        sSrc = oA.getElementsByTagName('img')[0].src;
        sSrc = sSrc.replace('WIDTH=133', 'WIDTH=300');
    }

    // center product preview image
    var oPreviewImage = document.createElement('img');
    oPreviewImage.src = sSrc;
    oPreviewImage.width = oA.pImageWidth * imageShrinkPerc;
    oPreviewImage.height = oA.pImageHeight * imageShrinkPerc;
    var left = 50 + parseInt((300 - oPreviewImage.width) / 2) + 'px';
    oPreviewImage.style.left = left;
    var top = addlOffset + 31 + parseInt((310 - oPreviewImage.height) / 2) + 'px';
    oPreviewImage.style.top = top;
    oPreviewImage.style.zIndex=0;
    oPreviewBubble.appendChild(oPreviewImage);
    //}

    // with the two lines uncommented, product image will hide preview bubble on mouse over
    //oPreviewImage.oA_id = oA.id;
    //oPreviewImage.onmouseover = productPreview.startHideTimers;

    // detect IE, but block IE7 (both bugs are fixed in IE7)
    if (document.attachEvent && !window.XMLHttpRequest) {
        // get url of productPreview background image
        var sSrcBG = oA.preview.currentStyle['backgroundImage'];
        sSrcBG = sSrcBG.substring(sSrcBG.lastIndexOf('images/'), sSrcBG.length - 2)
        oA.preview.style.backgroundImage = 'none';

        // attach filter to another DIV so that oPreviewBubble can still handle mouse clicks
        var oPreviewIEBackground = document.createElement('div');
        oPreviewIEBackground.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + sSrcBG + "')";
        // workaround for IE6 problems
        if (oA.pText) {
            oPreviewIEBackground.className = 'previewText';
            oPreviewIEBackground.innerHTML = oA.pText;
        }
        oPreviewBubble.appendChild(oPreviewIEBackground);

        //		// if the shield does not already exist, create it
        //		if ( !document.getElementById('productPreviewShield') )
        //		{
        //			// insert iframe to block select boxes from showing through menu
        //			var oFrame = document.createElement('iframe');
        //			oFrame.id = 'productPreviewShield';
        //			oFrame.src = "about:blank";
        //			oFrame.scrolling = "no";
        //			oFrame.frameborder = "0";
        //			oFrame.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
        //			document.body.appendChild(oFrame);
        //		}
    }
}

/**
* This function returns absolute position of product link so bubble can be placed correctly.
*/
productPreview.position = function( oA )
{
	var posT = posL = 0;
	if (oA.offsetParent)
	{
		posT = oA.offsetTop;
		posL = oA.offsetLeft;

		while (oA = oA.offsetParent)
		{
			posT += oA.offsetTop;
			posL += oA.offsetLeft;
		}
	}
	return [posT,posL];
}

/**
* This function shows the product preview.
*/
productPreview.show = function( oA )
{
	var aPos = productPreview.position( oA );

	var sPosT = (document.all ? aPos[0] - 53 + 'px' : aPos[0] - 163 + 'px'); // adjust for firefox
	var sPosL = aPos[1] + 133 + 'px';
	
	oA.preview.style.top  = sPosT;
	oA.preview.style.left = sPosL;
	oA.preview.style.display = 'block';
	
	var oShield = document.getElementById('productPreviewShield')
	if ( oShield )
	{
		oShield.style.top  = sPosT;
		oShield.style.left = sPosL;
		oShield.style.display = 'block';
	}
}

/**
* This function stops all timers and hides the preview.
*/
productPreview.startHideTimers = function()
{
	// used to pass object into timer functions
	var oA = this;

	//if ( this.nodeName != 'a' ) oA = document.getElementById(this.oA_id);
	
	// kill determineIntentTimer
	if ( oA.determineIntentInterval )
	{
		clearInterval(oA.determineIntentInterval);
		oA.determineIntentInterval = null;
	}

	// kill showPreviewTimer
	if ( oA.showPreviewTimer )
	{
		clearTimeout(oA.showPreviewTimer);
		oA.showPreviewTimer = null;
	}

	if ( oA.preview ) oA.hidePreviewTimer = setTimeout( function(){ productPreview.hide( oA ) }, 25 );
}

/**
* This function shows the product preview.
*/
productPreview.hide = function( oA )
{
	oA.preview.style.display = 'none';
	var oShield = document.getElementById('productPreviewShield')
	if ( oShield ) oShield.style.display = 'none';
}
