var isSafari = navigator.userAgent.indexOf("Safari") > -1 || navigator.userAgent.indexOf("AppleWebKit") > -1;
var d_bobMS = '700';
/* Constants */
var AXIS_X = 0;
var AXIS_Y = 1;

/* shortcut to getElementById */
function getNode(node) {
	return document.getElementById(node);
}


/* Destroy a node with the Death Star */
function killNode(nodeID) {
	var node = getNode(nodeID);
	var nodeParent = node.parentElement;
	if (typeof nodeParent != "undefined") {
		nodeParent.removeChild(node);
	} else {
		node.style.display = "none";
	}
}

/* Replace text in a node. */
function swapTextNode(parentObject, newText) {
    parentObject.replaceChild(document.createTextNode(newText), parentObject.firstChild);
}

/* Replace text in a node. Has more protection than the previous version and will fall back on non-DOM techniques if it can't pick out the childNodes */
function replaceInnerText(node, text) {
	//	replacement for node.innerHTML = text; which is apparently broken in Safari 1.2.4
	if (typeof node.childNodes != "undefined" && node.childNodes.length > 0) {
		var newnode = document.createTextNode(text);
		node.replaceChild(newnode, node.firstChild);
	} else {
		// fall back on the old school just in case
		node.innerHTML = text;
	}
}

/* Cross browser solution to DOM getComputedStyle() (Safari doesn't currently support this) */
function grabComputedStyle(elementObject) {

    if (document.defaultView && document.defaultView.getComputedStyle ) {
        return  document.defaultView.getComputedStyle(elementObject, null);
     } else if  (elementObject.currentStyle) {
        return elementObject.currentStyle;
    } else  {
        return null;
    }

}

function grabComputedHeight(elementObject) {

    var height = grabComputedStyle(elementObject).height;
    
    if (height != null) {
        if (height.indexOf("px") != -1)
            height = height.substring(0, height.indexOf('px'));
        if (height == "auto") {
            if (elementObject.offsetHeight)
                height = elementObject.offsetHeight + 10;
        }
    }
    
    return height;
    
}

/* Return the target node for an event. */
function getEventTarget(evt) {
	var tgt = evt.srcElement;
	if (!tgt)
		tgt = evt.target;
	return tgt;
}
function getWindowHeight() {
    var height = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
	    height = window.innerHeight;
	} else if( document.documentElement && document.documentElement.clientHeight) {
	    height = document.documentElement.clientHeight;
	} else if( document.body && document.body.clientHeight) {
	    height = document.body.clientHeight;
	}
    return height;
}

/* Clear out any text that may have been selected (called "ranges") by dragging the mouse mid-click. */

function clearRanges(event) {
	if (isMacIE) { // Mac IE is blowing up
	} else if (isSafari) { // Avoid Safari 1.3 / 2.0 bugs with window.getSelection()
		event.stopPropagation();
	} else if (document.selection) { // IE 6
		document.selection.empty();
	} else if (window.getSelection()) { // NS 6
		window.getSelection().removeAllRanges();
	} else {
		event.stopPropagation();
	}
}

/* How much the document's been scrolled vertically. Needed for correcting position calculations. */
function getDocumentScrollAmount() {
	if (!isSafari) {
		return document.body.scrollTop;
	} else {
		return 0;
	}
}

/* Computes the total vertical offset of a node, the sum of the enclosing objects' vertical offset. */
function getElementOffsetY(element) {
	var totalOffset = 0;
	if (element.offsetTop != null) {
        totalOffset += element.offsetTop;
		while (element.offsetParent) {
			totalOffset += element.offsetParent.offsetTop;
			element = element.offsetParent;
		}
	}
	return totalOffset;
}

function getElementMouseCoordinate(evt, curEmt) {
var xC = -1;  
    if (!evt) var evt = window.event;
    
    if (evt.offsetX) {
        xC = evt.offsetX;
    } else if (curEmt.offsetX != null) {
        eXC = curEmt.offsetX;
        xC = evt.layerX - eXC;
    } else if (evt.layerX) {
        eXC = getElementOffsetX(curEmt);
        xC = evt.layerX - eXC;
        curEmt.offsetX = eXC;
    }
    return xC;
}

/* Computes the total horizontal offset of a node, the sum of the enclosing objects' horizontal offset. */
function getElementOffsetX(element) {
    var totalOffset = 0;
    if (element.offsetLeft != null) {
        totalOffset += element.offsetLeft;
        while (element.offsetParent) {
            totalOffset += element.offsetParent.offsetLeft;
            element = element.offsetParent;
        }
    }
    return totalOffset;
}

/* Gets the position of the top of a node. */
function getNodeTop(nodeId) {
	var itemOver = document.getElementById(nodeId);
	var itemOverTop = itemOver.style.top ? (itemOver.offsetTop - stripUnits(itemOver.style.top)) : itemOver.offsetTop;
	return itemOverTop;
}


/* Moves an object vertically. Pass in either the node or the node's ID. If amount is positive, move it down. Negative? Move it up. */
function moveNode(mover, amount) {
	if (typeof mover == "string")
		mover = getNode(mover);
	
	if (mover.style.top) {
		mover.style.top = stripUnits(mover.style.top) + amount + "px";
	} else {
		mover.style.top = (amount) + "px";
	}
}

/* Debug utility; displays all of the properties of an object in a popup */
function displayObject(obj) {
	var msg = "";
	for (var prop in obj) {
		msg += prop;
		msg += ": ";
		msg += prop.value;
		msg += "\n";
	}
	window.alert(msg);
}

function tokenizeString(inputString, token) {
    var output = new Array();
    var counter = 0;
    if (inputString) {
        while (inputString.indexOf(token) != -1) {
            var end = inputString.indexOf(token);
            var newStart = end + token.length;
            output[counter] = inputString.substring(0,end);
            inputString = inputString.substring(newStart);
            counter++;        
        }
        output[counter] = inputString;
    }
    return output;
}

function xmlRequest() {
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		req.isDOM = true;
		return req;
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		return req;
	} else 
		return null;
}

function isXMLReady(xmlObject) {
	return (xmlObject.readyState == 4 && xmlObject.status == 200);
}

function initMovie(movieXml) {
    if (isXMLReady(movieXml)){
        bobBoxInfo.innerHTML = movieXml.responseText;	}
	return true;}
/* ************** START BOB ******************** */
var BOB_BOX_TOP_SHADOW_OFFSET = -10;
var BOB_BOX_WIDTH;
var BOB_MOVIE_TO_ARROW_SPACER = 25;
var BOB_DISPLAY_STYLE_DEFAULT = 0;
var BOB_DISPLAY_STYLE_LARGE_BOXSHOT = 1;
var BOB_DISPLAY_STYLE_TINY_BOXSHOT = 2;
var BOB_ARROW_HEIGHT_NO_SHADOW = 70;
var LARGE_BOXSHOT_WIDTH = 110;
var MED_BOXSHOT_WIDTH = 65;
var TINY_BOXSHOT_WIDTH = 50;



/* do BOB */
function dB(evt, thisMovie) {      
    if (d_bobMS != -1) {
        try {
            if (movie.tagName != "A")
            clearTimeout(clearBOBTimer);
        } catch (e){}
        movie = thisMovie;
        movie.onmouseout = clearBOB; 
	    movieItemId = movie.id;                
        movie.displayStyle = 0
        movie.mouseCoordX = getElementMouseCoordinate(evt, movie);
        if (bobBox.style.visibility != "visible")
            bobBoxshot.src = "../popup/images/1px.gif";
        if (movie.tagName != "A") {
	        bobArrow.onmouseover = cancelClearBOB;
	        bobArrow.onclick = handleBOBArrowClick;
	        bobArrow.onmouseout = clearBOB;
        }
		bobDisplay = setTimeout("initBOB()", d_bobMS);
    }
}

/*  If the movie is clicked within the arrowspace, use the movie's href */
function handleBOBArrowClick() {  
    if (movie.tagName == "A")
        document.location.href = movie.href;
    else if (movie.parentNode.tagName == "A")
        document.location.href = movie.parentNode.href;
}

function getElementHeightMidpoint(element, modifier) {
    
    var height = grabComputedHeight(element);  
    if (height == null) 
        return null;
    else  {
        var safeHeight = "" + height;
        if (safeHeight.indexOf('px') != -1) {
            height = safeHeight.substring(0, height.indexOf('px'));
            
        }
    }
    return height / 2;
}

function initBOB() {

    movie.isActive = true;
    var itemId = movie.id;
    if (movie.alt) {
	   movie.altBackup = movie.alt;
       movie.alt = "";
    }
	if (!movie.mtitle) {
		
        movie.movieId = itemId;
        movie.itemId = itemId;
        movie.dispStyle = 0;
        movie.position = 0;
        
        var linkCtrType = "BOX";
        if (movie.tagName == "A") 
            linkCtrType = "TXT";
                var url = "../../../ftdvida/popup/prodinfo.asp?arg=" + itemId;
        
		movieXml = new xmlRequest();
		movieXml.onreadystatechange = initBOBMovie;
		movieXml.open("GET", url, true);
		movieXml.send(null);		

	} else {
    
	    if (getBOBBoxshot(movie))
		  drawBOB();
	}
    return true;    
}

function getBOBBoxshot() {

    bobBoxshot.style.display = "inline";
    bobBoxshot.parentMovieId = movie.itemId;
    var boxMovieId = movie.movieId;
    if (movie.parentId)
        boxMovieId = movie.parentId;
            
    //bobBoxshot.src = IMAGE_ROOT + "boxshots/small/" + boxMovieId + ".jpg";    bobBoxshot.src = "../../../ftdvida/popup/pictbinary.asp?arg=" + boxMovieId         
    drawBOB();
            
    return true;
}
    
function initBOBMovie() {
    try {		if (isXMLReady(movieXml)) {
	        if (initMovie(movieXml))
	           getBOBBoxshot(); 
	    } 
    } catch (e) {}
}
function cancelClearBOB() {
    try {
    clearTimeout(clearBOBTimer);
    //movie.isActive = true;
    } catch (e) {}
}

function clearBOB() {
        clearBOBTimer = setTimeout("doClearBOB()", 3);
}

function doClearBOB() { 
        try {
	    movie.isActive = false;	    movie.className="P";
	    clearTimeout(bobDisplay);
	    movie.alt = movie.altBackup;
	    bobBox.style.visibility = "hidden";
	    bobBoxshot.style.display = "none";	    bobBoxInfo.innerHTML = "";
	    var emptyNodes = emptyBOBNodes();
        } catch (e) {}
}

function emptyBOBNodes() {
    return true;
}

function drawBOB() {     
    movie.drawingBOB = true;
    var emptyNodes = emptyBOBNodes();
    if (movie.isActive) { 
        setupBOBPosition(movie);      
    }
}

function getBOBYOverrunAdjustment(_computedHeight, movie) {
    var _winHeight = getWindowHeight();            
    var _scrollAmt = getDocumentScrollAmount();
    var _bobBoxTop = (getElementOffsetY(bobBox) - BOB_BOX_TOP_SHADOW_OFFSET) - _scrollAmt; // its okay for the shadow to bleed
    var _overrun = 0;
    
    
    var _bobBoxBottomPos = (_bobBoxTop * 1) + (_computedHeight * 1);
    bobBox.computedHeight = _computedHeight;
    
    if (_bobBoxBottomPos > _winHeight) {
        _overrun =  _bobBoxBottomPos - _winHeight - 30;
        // Fix for mozilla first time rendering boxshot funk 
        if (movie.tagName == "A" && movie.isDOM && !movie.MozAdjust) {
            //_overrun -= 85;
            //bobBox.computedHeight -= 85
            movie.MozAdjust = true;
        }
    }
    if (_bobBoxTop - _overrun < 1) {
        _overrun = _bobBoxTop;
    }
    
    return _overrun;
}

function getBOBTop(movie) {
    var _computedHeight = grabComputedHeight(bobBox);
    var _quarterHeight = _computedHeight / 4;
    var _elementY = getElementOffsetY(movie);
    var _topPosition = (_elementY + BOB_BOX_TOP_SHADOW_OFFSET) - _quarterHeight; //its okay for the shadow to bleed
    bobBox.style.top = _topPosition; // set so we can calculate overrun    
    _topPosition -= getBOBYOverrunAdjustment(_computedHeight, movie);    
    return _topPosition;
    
}

function getBOBLeft(movie) {
    
    
    var _pageMidpoint = getElementOffsetX(document.getElementById("page-content"));
    var _elementOffsetX = getElementOffsetX(movie);
    var _activeAreaWidth = 0;
    if (movie.tagName != "A") {
	    if (movie.displayStyle == BOB_DISPLAY_STYLE_LARGE_BOXSHOT)
	        _activeAreaWidth = LARGE_BOXSHOT_WIDTH;
	    else if (movie.displayStyle == BOB_DISPLAY_STYLE_TINY_BOXSHOT) 
	        _activeAreaWidth = TINY_BOXSHOT_WIDTH;
	    else
	        _activeAreaWidth = MED_BOXSHOT_WIDTH;
    } else {
        _activeAreaWidth = movie.mouseCoordX + 50; //50 is a buffer zone for the link
    }
    
	
    var _leftPosition = _elementOffsetX + BOB_MOVIE_TO_ARROW_SPACER + _activeAreaWidth;
		if (_leftPosition  > _pageMidpoint + 590) { // is beyond right buffer?
       _leftPosition -= BOB_BOX_WIDTH + BOB_MOVIE_TO_ARROW_SPACER + _activeAreaWidth + 20;
        bobBox.arrowSwap = true;
    } else {
        bobBox.arrowSwap = false;
    }    
    return _leftPosition;
}

function setupBOBPosition(movie) {

        var ARROW_BUFFER = 35;
        
        
        var winHeight = getWindowHeight();            
        var scrollAmt = getDocumentScrollAmount();
        var PAGE_MIDPOINT = getElementOffsetX(document.getElementById("page-content")) + 405;
        
        var WINDOW_TOP_PADDING = 4;
        var FALLBACK_MIDPOINT = 160;
        
        var dispStyleLeftAdjustment = 0;
        var dispStyleRightAdjustment = 0;
        
        bobBox.style.top = getBOBTop(movie);
        bobBox.style.left = getBOBLeft(movie);
        bobArrow.style.top = positionBOBArrow(movie);
                
        doDisplayBob = setTimeout("displayBOB('" + movie.itemId + "')", 5);
}

function positionBOBArrow(movie) {    

    var _isPointedUp = false;
    var _isPointedRight = bobBox.arrowSwap;
    var _elementY = getElementOffsetY(movie) - getElementOffsetY(bobBox);
    var _ARROW_HEIGHT = 101;
    var _arrowTop = _elementY;
    
    if (_arrowTop <  (bobBox.computedHeight / 2)) {
        _isPointedUp = true;
    } else {
        _arrowTop -= BOB_ARROW_HEIGHT_NO_SHADOW; 
    }
    // Make sure arrow doesn't overlap top and bottom and respects the top and bottom of BOB
    if (_arrowTop + _ARROW_HEIGHT + 10 > bobBox.computedHeight)  //10 is the padding we want to preserve at the bottom of the page.
        _arrowTop -= 10;
    if (_arrowTop < 10)
        _arrowTop = 10;


    if (_isPointedRight) {
        bobArrow.style.left = bobContentTable.width -15;
    } else {
        bobArrow.style.left = -40;
    }
    if (_isPointedUp && !_isPointedRight) {
         bobArrowULImg.style.display = "block";
         bobArrowURImg.style.display = "none";
         bobArrowLLImg.style.display = "none";
         bobArrowLRImg.style.display = "none";
    } else if (_isPointedUp && _isPointedRight) {
         bobArrowULImg.style.display = "none";
         bobArrowURImg.style.display = "block";
         bobArrowLLImg.style.display = "none";
         bobArrowLRImg.style.display = "none";
    } else if (!_isPointedUp && _isPointedRight) {
         bobArrowULImg.style.display = "none";
         bobArrowURImg.style.display = "none";
         bobArrowLLImg.style.display = "none";
         bobArrowLRImg.style.display = "block";
    } else {
        bobArrowULImg.style.display =  "none";
         bobArrowURImg.style.display = "none";
         bobArrowLLImg.style.display = "block";
         bobArrowLRImg.style.display = "none";

    }
	//if (arrowTop < 30) arrowTop = 30;   
     
    return _arrowTop;
}

function displayBOB(itemId) {
    movie = document.getElementById(itemId);
        if (movie.isActive) {
	    bobBox.style.visibility = "visible";

    }
}
function primeBOB() {
    bobBox = document.getElementById("bob");
    bobBoxshot = document.getElementById("bobimg");    bobBoxInfo = document.getElementById("bobinfo");
    bobArrow = document.getElementById("bobarrow");
    bobArrowULImg = document.getElementById("bobarrowulimg");
    bobArrowURImg = document.getElementById("bobarrowurimg");
    bobArrowLLImg = document.getElementById("bobarrowllimg");
    bobArrowLRImg = document.getElementById("bobarrowlrimg");    bobContentTable = document.getElementById("bobcontenttable");
    bobArrow.style.cursor = "pointer";
    window.onscroll = clearBOB;
    window.onblur = clearBOB;
	BOB_BOX_WIDTH = bobContentTable.width -1;		bobBox.style.visibility = "hidden";
}