// TODO: Double check that drags are locked, so the browser isn't in a "stuck" state
// TODO: In the future, OnUnload should save the cart (for "back" buttons, once we have more than one item page)
// Done: Non-PNG images for arrows, help arrow, cart icon
// Done: Branch code for all png's
// TODO: Rollovers for arrows?
// Done: Fix IE so the image is dragged by its center
// Done: Make Poof routine more flexible
// Done: Make SnapBack so that you pass it coordinates
// Done: Add "Clear Cart" button
// Done: Firefox bug when quickly dragging out and letting go of the mouse?
// TODO: Figure out why popups are unnecessarily easy to trigger in IE

// Some basic initalization / browser detection.

var isNav4, isIE4, isMac, isNav6;
if (parseInt(navigator.appVersion.charAt(0)) >= 4) {
  isStd = (navigator.appName == "Netscape") ? true : false
  isIE  = (navigator.appName.indexOf("Microsoft") != -1) ? true : false
  isMac = (navigator.platform.indexOf("Mac") != -1) ? true : false
  isPNG = (isIE && ! isMac) ? false : true
}

//window.onerror = trap_error;
//
//function trap_error(error, url, line) {
//	alert("There was an error from '" + url + "' at line '" + line + "'.\n\n" + error);
//	return true;
//}

// Initializations

var cartScroll            = 0;
var leftScrollAct         = 0;
var rightScrollAct        = 0;
var currentlyResizingFlag = 0;
var removeOccured         = 0;
var finalDestination      = "";
var flashCount			  = 0;

// PRELOAD the important images

if (isPNG) {
	poof1 = new Image(90,68); poof1.src = "/images/cart_fade1.png";
	poof2 = new Image(90,68); poof2.src = "/images/cart_fade2.png";
	poof3 = new Image(90,68); poof3.src = "/images/cart_fade3.png";
	poof4 = new Image(90,68); poof4.src = "/images/cart_fade4.png";
	poof5 = new Image(90,68); poof5.src = "/images/cart_fade5.png";
	poof6 = new Image(90,68); poof6.src = "/images/cart_fade6.png";
	poof7 = new Image(90,68); poof7.src = "/images/cart_fade7.png";
	poof8 = new Image(90,68); poof8.src = "/images/cart_fade8.png";
	poof9 = new Image(90,68); poof9.src = "/images/cart_fade9.png";

	cartl = new Image(51,50); cartl.src = "/images/cart_arrow_left.png";
	cartr = new Image(51,50); cartr.src = "/images/cart_arrow_right.png";
	cartldis = new Image(51,50); cartldis.src = "/images/cart_arrow_left_dis.png";
	cartrdis = new Image(51,50); cartrdis.src = "/images/cart_arrow_right_dis.png";
} else {
	// Replace with GIF's
	poof1 = new Image(90,68); poof1.src = "/images/cart_fade1.png";
	poof2 = new Image(90,68); poof2.src = "/images/cart_fade2.png";
	poof3 = new Image(90,68); poof3.src = "/images/cart_fade3.png";
	poof4 = new Image(90,68); poof4.src = "/images/cart_fade4.png";
	poof5 = new Image(90,68); poof5.src = "/images/cart_fade5.png";
	poof6 = new Image(90,68); poof6.src = "/images/cart_fade6.png";
	poof7 = new Image(90,68); poof7.src = "/images/cart_fade7.png";
	poof8 = new Image(90,68); poof8.src = "/images/cart_fade8.png";
	poof9 = new Image(90,68); poof9.src = "/images/cart_fade9.png";

	cartl = new Image(51,50); cartl.src = "/images/cart_arrow_left.png";
	cartr = new Image(51,50); cartr.src = "/images/cart_arrow_right.png";
	cartldis = new Image(51,50); cartldis.src = "/images/cart_arrow_left_dis.png";
	cartrdis = new Image(51,50); cartrdis.src = "/images/cart_arrow_right_dis.png"; 
}

////////////////
//
// CARTBAR related code
//
////////////////

// ANIMATE loading indicator
function animateIndicator() {
}

// FLASH the cart item

function flashCartThumb(theThumb, flashTotal) {
	//window.status = 'cartslot-'+theThumb+'-item';
	if (isStd) {
		obj = document.getElementById('cartslot-'+theThumb+'-item');
	} else {
		obj = document.all['cartslot-'+theThumb+'-item'];
	}

	// Total flashes achieved
	if (flashCount == flashTotal) {
		// Stop flashing
		clearInterval(flashTimer);
		flashCount = 0;
		obj.style.border = '0px';
	} else {
		//window.status = "Border: " + obj.style.borderLeftWidth;
		// Change flash status
		if (obj.style.borderLeftWidth == '1px') {
			obj.style.border = '0px';
		} else {
			obj.style.border = '1px solid #fff';
		}
		// Increment flash counter
		flashCount++;
	}
}

// ADD Item To Cart

function addToCart(theItemName) {

	// Check that the item is not already in the cart
	for ( var i = 0; i < orderedArray.length; i++ ) {
		if (orderedArray[i] == theItemName) {
			var thumbFlash;
			// Item already in the cart - scroll to it and make it flash!!
			if (i < (cartScroll + cartSpaces) && i >= cartScroll) {
				// Thumb already visible, just flash it
				thumbFlash = i - cartScroll;
			} else if (i < cartSpaces) {
				cartScroll = 0;
				thumbFlash = i;
			} else if ((i + cartSpaces) < orderedArray.length) {
				cartScroll = i;
				thumbFlash = 0;
			} else {
				cartScroll = i - cartSpaces + 1;
				thumbFlash = cartSpaces - 1;
			}

			// window.status = "Flash: " + thumbFlash;

			// Now, redraw the cart thumbs
			displayCartThumbs(cartScroll);

			// Now, flash the thumb containing the item we were trying to add
			flashTimer = setInterval("flashCartThumb("+thumbFlash+", 10)", 70);
			return;
		}
	}

    // Next, add the item to the array of ordered items
    orderedArray = orderedArray.concat(theItemName);
	
    // Then, add the product name to the array, if it exists
	if (document.getElementById) {
		if (document.getElementById(theItemName+"-var")) {
			varietyArray = varietyArray.concat(document.getElementById(theItemName+"-var").innerHTML);
		} else {
			varietyArray = varietyArray.concat("");
		}
	}

    // Then, display the thumbnails
    // - If we have more than we can dispaly, scroll to the right
    // - If we're already scrolled, reset view right
	
    if (orderedArray.length > cartSpaces) {
      cartScroll++;
      if (cartScroll != (orderedArray.length - cartSpaces)) {
        cartScroll = (orderedArray.length - cartSpaces);
      }
    }

    // Draw the thumbnails
	
    displayCartThumbs(cartScroll);

    // Draw the total

    displayTotalPrice();

	// Update database
	var params = '';
	var url = '/shop/add/'+theItemName;
	new Ajax.Request(url, {
		onLoading:function(request){
			if (isStd) {
				document.getElementById("cart_loading").style.display = "inline";
			} else {
				document.all["cart_loading"].style.display = "inline";
			}
		},
		onComplete:function(request){
			if (isStd) {
				document.getElementById("cart_loading").style.display = "none";
			} else {
				document.all["cart_loading"].style.display = "none";
			}
		},
		method: 'get',
		parameters: params,
		evalScripts:true,
		asynchronous:true
		});
}

// REMOVE Item From Cart

function removeFromCart(removedSlot) {

  // Iterate through the array of cart items, and remove SLOT + SCROLL
	
  var tempArray = new Array();
  var tempVarArray = new Array();

  for (var i=0; i < orderedArray.length; i++) {
    if (i != (parseInt(removedSlot) + parseInt(cartScroll))) { 
      // Not the one we removed, keep it in
      tempArray = tempArray.concat(orderedArray[i]);
      tempVarArray = tempVarArray.concat(varietyArray[i]);
    } else {
      removedItem = orderedArray[i];
      removedVar = varietyArray[i];
    }
  }

  orderedArray = tempArray;  
  varietyArray = tempVarArray;

  // Reduce the scroll pointer, if we're showing more than can fit
	
  if (orderedArray.length > (cartSpaces - 1) && cartScroll != 0) {
    // Note to self. cartSpaces - 1 exists above because the array starts at 0,
    // but the number of cart slots starts at 1. It was not setting the scroll
    // amount back to zero, ever, because the legnth of items was matching too soon.
    cartScroll--;
  }

  // Now, redraw the cart thumbs
	
  displayCartThumbs(cartScroll);

  // Draw the total

  displayTotalPrice();

	// Update database
	var params = '';
	new Ajax.Request('/shop/del/'+removedItem, {
		onLoading:function(request){
			if (isStd) {
				document.getElementById("cart_loading").style.display = "inline";
			} else {
				document.all["cart_loading"].style.display = "inline";
			}
		},
		onComplete:function(request){
			if (isStd) {
				document.getElementById("cart_loading").style.display = "none";
			} else {
				document.all["cart_loading"].style.display = "none";
			}
		},
		method: 'get',
		parameters: params,
		evalScripts:true,
		asynchronous:true
		});
}

function removeCartItem(theItemName) {

  // Iterate through the array of cart items, and remove SLOT + SCROLL
	
  var tempArray = new Array();
  var tempVarArray = new Array();

  for (var i=0; i < orderedArray.length; i++) {
    if (orderedArray[i] != theItemName) { 
      // Not the one we removed, keep it in
      tempArray = tempArray.concat(orderedArray[i]);
      tempVarArray = tempVarArray.concat(varietyArray[i]);
    } else {
      removedItem = orderedArray[i];
      removedVar = varietyArray[i];
    }
  }

  orderedArray = tempArray;  
  varietyArray = tempVarArray;

  // Reduce the scroll pointer, if we're showing more than can fit
	
  if (orderedArray.length > (cartSpaces - 1) && cartScroll != 0) {
    // Note to self. cartSpaces - 1 exists above because the array starts at 0,
    // but the number of cart slots starts at 1. It was not setting the scroll
    // amount back to zero, ever, because the legnth of items was matching too soon.
    cartScroll--;
  }

  // Now, redraw the cart thumbs
	
  displayCartThumbs(cartScroll);

  // Draw the total

  displayTotalPrice();

}

// CLEAR the entire cart

function clearCart() {

  cartScroll = 0;
  emptyArray = new Array();

  orderedArray = emptyArray;
  varietyArray = emptyArray;

  displayCartThumbs(cartScroll);
  displayTotalPrice();
	
	// Update database
	var params = '';
	new Ajax.Request('/shop/clear', {
		onLoading:function(request){
//			if (isStd) {
//				document.getElementById("cart_loading").style.display = "inline";
//			} else {
//				document.all["cart_loading"].style.display = "inline";
//			}
			Element.show("cart_loading");
		},
		onComplete:function(request){
//			if (isStd) {
//				document.getElementById("cart_loading").style.display = "none";
//			} else {
//				document.all["cart_loading"].style.display = "none";
//			}
			Element.hide("cart_loading");
		},
		method: 'get',
		parameters: params,
		evalScripts:true,
		asynchronous:true
		});
}

// DISPLAY TOTAL - Itereate, calculate, and draw the total price

function displayTotalPrice() {
  theTotal = 0;
  for (var i=0; i < orderedArray.length; i++) {

   // Get the price of the item

   for (var j=0; j < itemArray.length; j++) {
      if (itemArray[j] == orderedArray[i]) {
        thePrice = priceArray[j];
      }
    }

    // Add it up

    theTotal = theTotal + thePrice;
  }

  displayTotal = theTotal + "";

  if (theTotal > 100) {
    displayTotal = displayTotal.substring(0, displayTotal.length - 2) + "." + displayTotal.substring(displayTotal.length - 2, displayTotal.length);
  }

  // Display the updated total
  $('total').update(displayTotal);

  // Display total number of cart items
  if (orderedArray.length > 1) {
	$('num_items').update('clear all ' + orderedArray.length + ' items');
  } else {
	$('num_items').update('remove item');
  }
  
	
//  if (document.getElementById) {
//    document.getElementById('total').innerHTML = displayTotal;
//  }

  return;
}

// DISPLAY THUMBS - Iterate through and display the thumbnails
// Both change the src image, and display the image itself via CSS

function displayCartThumbs(cartStartPos) {

	// cartStartPos = the item to show on the left edge (if more than 8 presumably)

	// Should we turn off the help text?

	if (orderedArray.length > 0) {
		if (isStd) {
		  document.getElementById("cart_help").style.display = "none";
		  document.getElementById("cartcontents").style.display = "inline";
		  document.getElementById("carthelp2").style.display = "inline";
		  document.getElementById("carthelp1").style.display = "none";
		} else {
		  document.all["cart_help"].style.display = "none";
		  document.all["cartcontents"].style.display = "inline";
		  document.all["carthelp2"].style.display = "inline";
		  document.all["carthelp1"].style.display = "none";
		}
//		Element.hide('cart_help');
//		Element.hide('carthelp1');
//		Element.show('cartcontents');
//		Element.show('carthelp2');
	}
	
  // Now go through and draw each of the items

  var j=0; // J is the number of the cart image we're working with
	
  for (var i = cartStartPos; i < (cartStartPos + cartSpaces); i++) {
    if (orderedArray[i]) {
		 if (isStd) {
			document.getElementById("cartslot-"+j+"-item").style.backgroundImage = "url(/images/themes/cart/"+orderedArray[i]+".jpg)";
			document.getElementById("cartslot-"+j+"-item").style.width = "90px";
			document.getElementById("cartslot-"+j+"-title").setAttribute("tip", varietyArray[i]);
		 } else {
			document.all["cartslot-"+j+"-item"].style.backgroundImage = "url(/images/themes/cart/"+orderedArray[i]+".jpg)";
			document.all["cartslot-"+j+"-item"].style.display = "inline";
			document.all["cartslot-"+j+"-title"].setAttribute("tip", varietyArray[i]);
		 }
//			Element.setStyle("cartslot-"+j+"-item", {
//				backgroundImage: 'url(images/themes/cart/'+orderedArray[i]+'.jpg)',
//				width: '90px';
//			});
//			document.getElementById("cartslot-"+j+"-title").setAttribute("tip", varietyArray[i]);
    } else {
		if (isStd) {
			document.getElementById("cartslot-"+j+"-item").style.display = "none";
			document.getElementById("cartslot-"+j+"-item").style.width = "0px";
			document.getElementById("cartslot-"+j+"-item").style.backgroundImage = "url(/images/spacer.gif)";
			document.getElementById("cartslot-"+j+"-title").setAttribute("tip", "");
		} else {
			document.all["cartslot-"+j+"-item"].style.display = "none";
			document.all["cartslot-"+j+"-item"].style.backgroundImage = "url(/images/spacer.gif)";
			document.all["cartslot-"+j+"-title"].setAttribute("tip", "");
		}		
//			Element.setStyle("cartslot-"+j+"-item", {
//				backgroundImage: 'url(images/spacer.gif)',
//				width: '0px';
//			});
//			Element.hide("cartslot-"+j+"-item");
    }
    j++;
  }

  // Do we need to display the left arrow?
  if (cartStartPos > 0) {
    if (document.images["cartleft"].src != cartl.src) {
      document.images["cartleft"].src = cartl.src;
    }
    leftScrollAct = 1;
  } else {
    if (document.images["cartleft"].src != cartldis.src) {
      document.images["cartleft"].src = cartldis.src;
    }
    leftScrollAct = 0;
  }
	
  // Do we need to display the right arrow?
  if ((cartStartPos + cartSpaces) < orderedArray.length) {
    if (document.images["cartright"].src != cartr.src) {
      document.images["cartright"].src = cartr.src;
    }
    rightScrollAct = 1;
  } else {
    if (document.images["cartright"].src != cartrdis.src) {
        document.images["cartright"].src = cartrdis.src;
    }
    rightScrollAct = 0;
  }

  // Should we turn on the help layer?
  if (orderedArray.length == 0) {
    if (isStd) {
      document.getElementById("cart_help").style.display = "inline";
      document.getElementById("cartcontents").style.display = "none";
      document.getElementById("carthelp2").style.display = "none";
	  document.getElementById("carthelp1").style.display = "inline";
    } else {
      document.all["cart_help"].style.display = "inline";
      document.all["cartcontents"].style.display = "none";
      document.all["carthelp2"].style.display = "none";
	  document.all["carthelp1"].style.display = "inline";
    }
//		Element.show('cart_help');
//		Element.show('carthelp1');
//		Element.hide('cartcontents');
//		Element.hide('carthelp2');
  }
  return;
}

// SCROLL the cart view left
function scrollCartLeft() {
  // Only if the arrow is active, as determined by displayCartThumbs
  if (leftScrollAct == 0) {
    return;
  } else {
    cartScroll--;
    displayCartThumbs(cartScroll);
  }
}

// SCROLL the cart view right

function scrollCartRight() {
  // Only if the arrow is active, as set by displayCartThumbs
  if (rightScrollAct == 0) {
    return;
  } else {
    cartScroll++;
    displayCartThumbs(cartScroll);
  }
}

////////////////
//
// DRAGGING / DROPPING related code
//
////////////////

var cartLayer = "cart";
var dragLayer = "ItemDrag";
var dragImage = "DragImage";
var highlightElement = "cart_contents";

// ROLLOVER - Layer capable rollover function

function hiLite(imgDocID, imgObjName, imgLayerID) {
  if (imgLayerID) {
     if (isStd) {
        theObj = document.getElementById(imgDocID);
        theObj.setAttribute("src", eval(imgObjName + ".src"));
     }
     else {
       document.all[imgLayerID].document.images[imgDocID].src = eval(imgObjName + ".src");
     }
  }
  else {
    document.images[imgDocID].src = eval(imgObjName + ".src");
  }
} 

var oldX, oldY, movingStatus, layerClicked, what, clickURL, helpUp;

// SHOW/HIDE - This will show/hide an element

function toggleVisibility(what, show) {

   // alert("Here");

   if (show == 0) {
		if (isStd) {
			theObj = document.getElementById(what);
			if (theObj.style.visibility == "hidden" || theObj.style.visibility == "") {
				theObj.style.visibility = "visible";
				//window.status = "Object shown...";
			} else {
				theObj.style.visibility = "hidden";
				//window.status = "Object hidden...";
			}
		} else {
			if (document.all[what].style.visibility == "hidden" || document.all[what].style.visibility == "") {
				document.all[what].style.visibility = "visible";
			} else {
				document.all[what].style.visibility = "hidden";
			}
		}
   } else {
	   if (isStd) {
			theObj = document.getElementById(what);
			theObj.style.visibility = show;
		} else {
			document.all[what].style.visibility = show;
		}
   }   
}

// MOUSEDOWN
// See if we've clicked something that should be dragged, and if so, init the drag

function doDown(e) {
  
  // Calculate the mouse's click position

  if (isStd) {
    theTarget = e.target;
    xWin = e.pageX;
    yWin = e.pageY;
  } else {
    theTarget = window.event.srcElement;
    xWin = window.event.clientX;
    yWin = window.event.clientY + document.body.scrollTop;    
  }

  // Get the name of what we've clicked, and initialize a drag
  //
  // If it has "-drag" in the name, we know this is something to be dragged
  // The part before the "-drag" is used to set the proper drag image
  // I.e., "shirt-drag" would be the source image ID
  // "images-items/shirt/drag.png" would be the drag image

  if (theTarget.name && theTarget != "") {
    if (theTarget.name.indexOf("-drag") != -1 && movingStatus == "drag") {
    	// alert("A drag is already active / finishing!");
    }
    if (theTarget.name.indexOf("-drag") != -1) {
  
	  // Clear some things just in case
  
      itemName = "";
      itemCartSlot = "";
      layerClicked = "";
      theLayer = "";
    
      // Get the itemname from the image 'name' tag, in 95% of the cases
  
      itemName = theTarget.name.substring(0,theTarget.name.lastIndexOf("-"));
      
      // However, if it's a dynamic shopping cart thumb, get it from the array
      
      if (itemName.indexOf("cartslot") != -1) {
        // Determine which thumb was chosen, add the scroll offset to get the item name 
      	itemCartSlot = theTarget.name.substring(theTarget.name.indexOf("-") + 1, theTarget.name.lastIndexOf("-"));
      	itemName = orderedArray[parseInt(itemCartSlot) + parseInt(cartScroll)];
      }
    
	  // Initialize some stuff.
	  // "ItemDrag" is the hard-coded DIV we're using that contains the dragging picture
      // Since only one layer drags on this page, we assume it to be the value of "dragLayer".      

      layerClicked = dragLayer;
      
      // Grab the layer
      
      if (isStd) { 
        theLayer = document.getElementById(layerClicked);
        // alert("Layer: " + layerClicked + " Object: " + theLayer + " Left: " + theLayer.style.left);
      }

		//theLayer = $(layerClicked);
            
      // Find out what button was pressed -- only drag if it's the left
      
      if (isStd) {
        theButton = e.which;
      } else {
        theButton = event.button;
      }
      
      // If it's the left... do it!
      
      if (theButton == 1) {
  
        // Set the Icon to the right drag image
        // Test it, and only change it if it actually needs to be changed
        // Also get half the width and the height of the image being dragged, for layer calcuations.
 
        if (isIE) {

          dragImageWidth = Math.round(document.images[dragImage].width / 2);
          dragImageHeight = Math.round(document.images[dragImage].height / 2);
 
          if (isMac) {
            if (document.images[dragImage].src.indexOf("/images/themes/cart/"+itemName+".jpg") == -1) {
				document.images[dragImage].src = "/images/themes/cart/"+itemName+".jpg";
            }
          } else {
            if (document.images[dragImage].src.indexOf("/images/themes/cart/"+itemName+".jpg") == -1) {
				document.images[dragImage].src = "/images/themes/cart/"+itemName+".jpg";
            }
          }
        }
        if (isStd) {

          theObj = document.getElementById(dragImage);
		  if (theObj.getAttribute("src") != "/images/themes/cart/"+itemName+".jpg") {
            theObj.setAttribute("src", "/images/themes/cart/"+itemName+".jpg");
          }

          dragImageWidth = Math.round(theObj.getAttribute("width") / 2);
          dragImageHeight = Math.round(theObj.getAttribute("height") / 2);

          // Object's style.left can't be read until it is first set
          // We move it up and to the left half of the item's size, so the drag is from the item's middle
          // TODO: This should be dynamically calculated, really!
          
          theLayer.style.left = xWin - dragImageWidth;
          theLayer.style.top = yWin - dragImageHeight;
        }

        // Start Drag
 
        movingStatus = "drag";
              	 
      	// Now initialize mouse tracking, and set the first position for dragging
        
        if (isStd) { 
  	  	  document.captureEvents(Event.MOUSEMOVE);
          oldX = e.clientX;
          oldY = e.clientY;
          startX = parseInt(theLayer.style.left)
	  	  startY = parseInt(theLayer.style.top)
        } else {
	      oldX = window.event.offsetX;
	      oldY = window.event.offsetY;
        }
                      
      	// Set the INITIAL drag icon layer to the mouse position
        // Also, get the initial position for snapback
       
    	if (isStd) {

          // Also, get the initial position for snapback

    	  snapStartX = parseInt(theLayer.style.left);
    	  snapStartY = parseInt(theLayer.style.top); 
   		}
  		else {
    	    if (isMac) {
     		  document.all[layerClicked].style.pixelLeft = window.event.clientX - dragImageWidth;
      		  document.all[layerClicked].style.pixelTop  = (window.event.clientY) - dragImageHeight;
      		  snapStartX = document.all[layerClicked].style.pixelLeft;
      		  snapStartY = document.all[layerClicked].style.pixelTop;
     		} else {
      		  document.all[layerClicked].style.pixelLeft = window.event.clientX - dragImageWidth;
      		  document.all[layerClicked].style.pixelTop  = (window.event.clientY) + document.body.scrollTop - dragImageHeight;
      		  snapStartX = document.all[layerClicked].style.pixelLeft;
      		  snapStartY = document.all[layerClicked].style.pixelTop;
      		}
    	}    
         
        dropperHighlight = 0;
        removeHighlight = 0;
        layerShowing = "false";
         
		document.onmousemove = drag;
	     
        return false;
      }
    } else {
		movingStatus = "false";
	}
  }
}

// DRAGGING

function drag(e) {

  if (movingStatus == "drag") {
     // window.status = "Dragging...";
    
    // First, is the window still hidden? If so, show it.
    
    if (layerShowing == "false") {
       toggleVisibility(layerClicked, "visible");
       layerShowing = "true";
    }
     
    // Now, actually move the layer
    
    if (isStd) {
      // Nav6: Track the difference, and add the starting position to it  
      theLayer.style.left = startX + e.clientX - oldX;
      theLayer.style.top = startY + e.clientY - oldY;
      // window.status = "DRAG! Start: " + startX + "," + startY + " - Pg: " + e.pageX + "," + e.pageY + " - Old: " + oldX + "," + oldY + " - L/T: " + theLayer.style.left + "," + theLayer.style.top + " TEST: " + document.body.scrollTop;
    } else {
      if (isMac) {
        document.all[layerClicked].style.pixelLeft = window.event.clientX - dragImageWidth;
        document.all[layerClicked].style.pixelTop  = (window.event.clientY) + document.body.scrollTop - dragImageHeight;
        // window.status = "Drag On: " + window.event.clientX + " / " + window.event.clientY + " - " + oldX + " / " + oldY;
      }
      else {
        // On windows, the Y is fixed not relative to page scroll, so compensate
        document.all[layerClicked].style.pixelLeft = window.event.clientX - dragImageWidth;
        document.all[layerClicked].style.pixelTop  = (window.event.clientY) + document.body.scrollTop - dragImageHeight;
      }
    }
    
    // Now, check for the drop target.
    // Get the current location of the pointer...
    
    if (isStd) {
      currentX = e.pageX;
      currentY = e.pageY;
    }
    if (isIE) {
      currentX = window.event.clientX;
      currentY = window.event.clientY + document.body.scrollTop;
    }
    
    // Now, get the top edge of the drop layer, accounting for any amount of scroll
    
    if (isStd) {
      dropID = document.getElementById(cartLayer);
      dropperY = dropID.offsetTop + document.body.scrollTop;
    }
    if (isIE) {
      dropID = document.getElementById(cartLayer);
      dropperY = dropID.offsetTop;
    }

    // window.status = "Drag! " + currentX + "/" + currentY + " - " + dropperY + " - " + dropID.offsetTop;
    
    // Now, we split depending on if we're to be dragging IN or OUT.

    if (theTarget.name.indexOf("cartslot") != -1) {

      // OUT - We are dragging an item OUT of the cart, since "cartslot" is in the name of what we're dragging.
	  // So, if the mouse has moved above the "cart" area...

      if (currentY < dropperY) {

		// Only do this once
	
		if (removeHighlight != 1) {
		  // The item left the cart, so setting this flag will remove it when the drag is done
	
		  removeHighlight = 1;
		  removeOccured = 1;
	
		  // Now make this slot temporarily "dissapear" and slide it out by shrinking its width
	
		  //document.getElementById("cartslot-"+itemCartSlot+"-item").style.visibility = "hidden";
		  if (currentlyResizingFlag != 1 && rightScrollAct == 0 && leftScrollAct == 0) {
		    resizeTimer = setInterval("resizeWidthElement('cartslot-"+itemCartSlot+"-item', 0, -15)", 25);
		  }
		}
      } else {
		if (removeHighlight != 0) {
		  // The item is still in the cart, so don't remove it when the drag is done!
		
		  removeHighlight = 0;
		
		  // Slide the slot back in, but don't show the image again until it's dropped
		  // document.getElementById("cartslot-"+itemCartSlot+"-item").style.visibility = "visible";
		  // document.getElementById("cartslot-"+itemCartSlot+"-qty").style.visibility = "visible";
		  // document.getElementById("cartslot-"+itemCartSlot+"-var").style.visibility = "visible";
		
		  if (currentlyResizingFlag != 1 && rightScrollAct == 0 && leftScrollAct == 0) {
		    resizeTimer = setInterval("resizeWidthElement('cartslot-"+itemCartSlot+"-item', cartSlotSize, 15)", 25);
		  }
		}
      }
    } else {

      // IN - We're dragging an item INTO the cart

      if (currentY > dropperY) {
	    // The mouse is in, so highlight!
		dropperHighlight = 1;
		hiElem = document.getElementById(highlightElement);
		hiElem.style.backgroundPosition = '0px -110px';
	  } else {
		dropperHighlight = 0;
		hiElem = document.getElementById(highlightElement);
		hiElem.style.backgroundImage = "url(/images/bottom_bar_bg.jpg)";
		hiElem.style.backgroundPosition = '0px 0px';
      }
    }

    return false;
  }
}

// MOUSEUP
// Do something once the mouse is released

function doUp(e) {
  if (movingStatus == "drag") {

    // Did the user simply click the item? If so, take them where they want to go (if anywhere)

    if (isStd) {

      // alert(oldX + " and " + e.clientX + " and " + oldY + " and " + e.clientY);

      if (oldX == e.clientX && oldY == e.clientY) {
      // if (e.clientX < (oldX + 10) && e.clientX > (oldX - 10) && e.clientY < (oldY + 10) && e.clientY > (oldY - 10)) {

         // Turn off the drag layer
      
         if (layerShowing == "true") {
           layerShowing = "false";
           toggleVisibility(layerClicked, false);
         }
         movingStatus = "false";
         document.onmousemove = null;

	 if (finalDestination != "") {
	   eval(finalDestination);
           // finalDestination = "";
	 }

         return false;
      }
    } else {
      if (oldX == window.event.offsetX && oldY == window.event.offsetY) {
      // if (window.event.offsetX < (oldX + 10) && window.event.offsetX > (oldX - 10) && window.event.offsetY < (oldY + 10) && window.event.offsetY > (oldY - 10)) {
         if (layerShowing == "true") {
           layerShowing = "false";
           toggleVisibility(layerClicked, false);
         }
         movingStatus = "false";
         document.onmousemove = null;

	 if (finalDestination != "") {
	   eval(finalDestination);
           // finalDestination = "";
	 }

         return false;

      }
    }
   
    // Drag has ended. Tear down events and such.

    document.onmousemove = null;
    
    // Did the icon reach any drag target?
    
    if (dropperHighlight == 1) {
	
        // ADD THE THING TO THE CART HERE
		
		addToCart(itemName);

        // Clear everything out
			
        dropperHighlight = 0;	
        hiElem = document.getElementById(highlightElement);
		hiElem.style.backgroundImage = "url(/images/bottom_bar_bg.jpg)";
		hiElem.style.backgroundPosition = '0px 0px';
	  	
        toggleVisibility(layerClicked, false);
	  	
        layerShowing = "false";
        movingStatus = "false";

    }
    else if (removeHighlight == 1) {

	// Stop resizing (sliding) an element, if we still are

	if (currentlyResizingFlag == 1) {
	    clearInterval(resizeTimer);
	    currentlyResizingFlag = 0;
	    // window.status = "RESIZE DONE";
        }

    	// Animate the poof
    
    	poofCount = 0;
        poofTimer = setInterval("animatePoof(dragImage)", 40);

        // Show the cart slot layer again (since it was likely hidden during the drag out)

        document.getElementById("cartslot-"+itemCartSlot+"-item").style.width = cartSlotSize;
        document.getElementById("cartslot-"+itemCartSlot+"-item").style.visibility = "visible";

        // REMOVE THE ITEM FROM THE CART
    	
        removeFromCart(itemCartSlot);
        removeHighlight = 0;
    }
    
    // If not, animate "snapping back", but only if the DIV actually moved!
    
    else {
      if (isStd) {
        snapEndX = parseInt(theLayer.style.left);
        snapEndY = parseInt(theLayer.style.top);  
        snapCurrent = 0;     
        snapTimer = setInterval("snapBack(layerClicked, snapStartX, snapStartY, snapEndX, snapEndY, 15)", 10);
      }
      else {
        snapEndX = document.all[layerClicked].style.pixelLeft;
        snapEndY = document.all[layerClicked].style.pixelTop;   
        snapCurrent = 0;     
        snapTimer = setInterval("snapBack(layerClicked, snapStartX, snapStartY, snapEndX, snapEndY, 15)", 10);
      }

		// If a cart slot was hidden via drag out but not completed, make it re-appear after the snap-back
		if (currentlyResizingFlag == 1) {
			clearInterval(resizeTimer);
			currentlyResizingFlag = 0;
			// window.status = "RESIZE DONE";
		}
		if (removeOccured == 1) {
			document.getElementById("cartslot-"+itemCartSlot+"-item").style.width = cartSlotSize;
			document.getElementById("cartslot-"+itemCartSlot+"-item").style.visibility = "visible";
		}
    }

    // Reset any flags

    removeOccured = 0;
    
    // Return click if all else fails.
    
    return false;
  }
}

// SNAPBACK v2 - The Snapback Animation Routine

function snapBack(layerToSnap, startX, startY, endX, endY, steps) {

   snapCurrent++;

   if (snapCurrent == 1) {
       multi = 0;
   } else { 
       multi = (1 - Math.pow(0.9, snapCurrent - 1)) / (1 - Math.pow(0.9, steps - 1));
   }

   snapX = endX + (startX - endX) * multi;
   snapY = endY + (startY - endY) * multi;

   // alert("Snap Back Step #" + snapCurrent + "/" + steps + " (move to " + snapX + " / " + snapY);
 
   if (isStd) {
     document.getElementById(layerToSnap).style.left = snapX;
     document.getElementById(layerToSnap).style.top = snapY;
   }
   else {
      document.all[layerToSnap].style.pixelLeft = snapX;
      document.all[layerToSnap].style.pixelTop = snapY;
   }
   
   if (snapCurrent == steps) {
     clearInterval(snapTimer);
     // window.status = "Snap complete.";
     toggleVisibility(layerToSnap, false);
     layerShowing = "false";
     movingStatus = "false";
   }
}

// POOF - Animate a Poof Ourselves (until animated .png's are standard!)

function animatePoof(imageToPoof) {

   poofCount++;

   if (poofCount == 10) {
     document.images[imageToPoof].src = "/images/spacer.gif";
     clearInterval(poofTimer);
     toggleVisibility(layerClicked, false);
     layerShowing = "false";
     movingStatus = "false";
   }
   else {
     document.images[imageToPoof].src = eval("poof"+poofCount+".src");
   }
}

// RESIZE - Resize any item over a period of time
//
// To be called by a setInterval() call. I.e.:
// resizeTimer = setInterval("resizeWidthElement('testimg', 500, 10)", 50);
// Pass me the item to be resized, the goal size, and the amount to resize each interval
// If you want me smaller, make rszAmount a negative number!

function resizeWidthElement(theID, rszGoal, rszAmount) {
	currentlyResizingFlag = 1;

	if (isStd) {
		rszElement = document.getElementById(theID);
	} else {
		rszElement = document.getElementById(theID);
	}

	if ((rszAmount < 0 && (parseInt(rszElement.style.width) + rszAmount) <= rszGoal) || (rszAmount > 0 && (parseFloat(rszElement.style.width) + rszAmount) >= rszGoal)) {
		rszElement.style.width = rszGoal;
		clearInterval(resizeTimer);
		currentlyResizingFlag = 0;
	} else {
		if (isNaN(parseInt(rszElement.style.width))) {
			rszElement.style.width = cartSlotSize
		}
		rszElement.style.width = parseInt(rszElement.style.width) + rszAmount;
		//rszElement.style.width = '10px';
	}
}

// POPUP - Open a popup / more information window

function openWindow(url, winWidth, winHeight) {
  if (screen.availWidth) {
    var screenPosX, screenPosY;
    screenPosX = Math.round((screen.availWidth - winWidth) / 2);
    screenPosY = Math.round((screen.availHeight - winHeight) / 2);
    newWin = window.open(url, 'subwin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0, copyhistory=0,width='+winWidth+',height='+winHeight+',left='+screenPosX+',top='+screenPosY+'');    
  }
  else {
    newWin = window.open(url, 'subwin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0, copyhistory=0,width='+winWidth+',height='+winHeight);
  }
}

// Initialize the Events!

document.onmousedown=doDown;
document.onmouseup=doUp;
