
// 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
}

// Initializations

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

// PRELOAD the important images

if (isPNG) {
  poof1 = new Image(64,64); poof1.src = "images/poof-1.png";
  poof2 = new Image(64,64); poof2.src = "images/poof-2.png";
  poof3 = new Image(64,64); poof3.src = "images/poof-3.png";
  poof4 = new Image(64,64); poof4.src = "images/poof-4.png";
  poof5 = new Image(64,64); poof5.src = "images/poof-5.png";

  cartl = new Image(20,55); cartl.src = "images/cart-leftarrow.png";
  cartr = new Image(20,55); cartr.src = "images/cart-rightarrow.png";
  cartldis = new Image(20,55); cartldis.src = "images/cart-leftarrow-dis.png";
  cartrdis = new Image(20,55); cartrdis.src = "images/cart-rightarrow-dis.png"; 
} else {
  poof1 = new Image(64,64); poof1.src = "images/poof-1.gif";
  poof2 = new Image(64,64); poof2.src = "images/poof-2.gif";
  poof3 = new Image(64,64); poof3.src = "images/poof-3.gif";
  poof4 = new Image(64,64); poof4.src = "images/poof-4.gif";
  poof5 = new Image(64,64); poof5.src = "images/poof-5.gif";

  cartl = new Image(20,55); cartl.src = "images/cart-leftarrow.gif";
  cartr = new Image(20,55); cartr.src = "images/cart-rightarrow.gif";
  cartldis = new Image(20,55); cartldis.src = "images/cart-leftarrow-dis.gif";
  cartrdis = new Image(20,55); cartrdis.src = "images/cart-rightarrow-dis.gif";
}

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

// ADD Item To Cart

function addToCart(theItemName,itemQty) {
    // Next, add the item to the array of ordered items	
	for(i=0;i<itemQty;i++){
		if(isEmpty()){
			orderedArray = orderedArray.concat(theItemName);
			orderedImgArray  = orderedImgArray.concat(itemImgArray[theItemName]);
		
			// Then, add the quantity and size to their arrays, if they exist
			if (document.orderform[theItemName+"-var"]) {
				varietyArray = varietyArray.concat(document.orderform[theItemName+"-var"].value);
			} else {
				varietyArray = varietyArray.concat("");
			}

			if (document.orderform[theItemName+"-qty"]) {
				quantityArray = quantityArray.concat(document.orderform[theItemName+"-qty"].value);
			} 
			/*else if(document.getElementById('prodQty')){
				quantityArray = quantityArray.concat(document.getElementById('prodQty').value);
				//alert(document.getElementById('prodQty').value)
			}		*/
			else {
				quantityArray = quantityArray.concat(1);
			}
			// 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);
				}
			}
		}else{
			break;
		}
	}
    // Draw the thumbnails
    displayCartThumbs(cartScroll);

    // Draw the total
    displayTotalPrice();
		
    // Update the cookie
    setCartCookie();
		addCount(itemIdArray[theItemName],itemQty);
}
	
// REMOVE Item From Cart
function removeFromCart(removedSlot) {
  // Iterate through the array of cart items, and remove SLOT + SCROLL	
  var tempArray = new Array();
  var tempQtyArray = new Array();
  var tempVarArray = new Array();
	var tempImgArray = 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]);
      tempQtyArray = tempQtyArray.concat(quantityArray[i]);
      tempVarArray = tempVarArray.concat(varietyArray[i]);
			tempImgArray = tempImgArray.concat(orderedImgArray[i]);
    } else {
      removedItem = orderedArray[i];
      removedQty = quantityArray[i];
      removedVar = varietyArray[i];
      removedImg = orderedImgArray[i];			
    }
  }

  orderedArray = tempArray;  
  quantityArray = tempQtyArray;
  varietyArray = tempVarArray;
  orderedImgArray = tempImgArray; 

  // 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 the cookie
  setCartCookie();
}

// CLEAR the entire cart

function clearCart() {
  var cartScroll = 0;	
	/*poofCount = 0;
	for (var i=0; i < orderedArray.length; i++){
	poofTimer = setInterval("animatePoofForAll("+i+")", 125);
	}*/
  emptyArray = new Array();

  orderedArray = emptyArray;
  quantityArray = emptyArray;
  varietyArray = emptyArray;
	orderedImgArray = emptyArray;

  displayCartThumbs(cartScroll);
  displayTotalPrice();
  setCartCookie();
}



// 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 = parseFloat(theTotal) + (parseFloat(thePrice) * parseInt(quantityArray[i]));
		theTotal = Math.round(theTotal*100)/100;
  }
	
	theTotal = formatAsMoney(theTotal);
  displayTotal = theTotal + "";

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

  // Display the updated total in the DIV	
  if (document.getElementById) {
    document.getElementById('total').innerHTML = displayTotal;
  }
	if (document.getElementById) {
    document.getElementById('item-count').innerHTML = i;
		document.getElementById('boxItemCount').value = i;
  }
	if(i==cartSpaces){
		document.getElementById('Image58').src = 'images/addtocart_ro.jpg';
	}else{
		document.getElementById('Image58').src = 'images/addtocart.jpg';
	}
  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("carthelp").style.visibility = "hidden";
      document.getElementById("cartcontents").style.visibility = "visible";
      document.getElementById("carthelp2").style.visibility = "visible";
    }
    else {
      document.all["carthelp"].style.visibility = "hidden";
      document.all["cartcontents"].style.visibility = "visible";
      document.all["carthelp2"].style.visibility = "visible";
    }
  }
	
  // 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]) {    
      // IE MAC doesn't support transparent .png's for background images, so we use GIFs instead.    
      if (isPNG && ! (isIE && isMac)) {
        document.getElementById("cartslot-"+j+"-item").style.backgroundImage = "url(product_images/thumb/"+orderedImgArray[i]+")";
				
        if (varietyArray[i]) {
	       document.getElementById("cartslot-"+j+"-var").style.backgroundImage = "url(images/var-"+varietyArray[i]+".png)";
        } else {
           document.getElementById("cartslot-"+j+"-var").style.backgroundImage = "url(images/spacer.gif)";
        }
        if (quantityArray[i] && quantityArray[i] > 1 && varietyArray[i]) {
            document.getElementById("cartslot-"+j+"-qty").style.backgroundImage = "url(images/qtyl-"+quantityArray[i]+".png)";
        } else if (quantityArray[i] && quantityArray[i] > 1 && ! varietyArray[i]) {
            document.getElementById("cartslot-"+j+"-qty").style.backgroundImage = "url(images/qtyr-"+quantityArray[i]+".png)";
        } else {
            document.getElementById("cartslot-"+j+"-qty").style.backgroundImage = "url(images/spacer.gif)";
        }
      } else {
        document.getElementById("cartslot-"+j+"-item").style.backgroundImage = "url(product_images/thumb/"+orderedImgArray[i]+")";
        if (varietyArray[i]) {
	       document.getElementById("cartslot-"+j+"-var").style.backgroundImage = "url(images/var-"+varietyArray[i]+".gif)";
        } else {
           document.getElementById("cartslot-"+j+"-var").style.backgroundImage = "url(images/spacer.gif)";
        }
        if (quantityArray[i] && quantityArray[i] > 1 && varietyArray[i]) {
            document.getElementById("cartslot-"+j+"-qty").style.backgroundImage = "url(images/qtyl-"+quantityArray[i]+".gif)";
        } else if (quantityArray[i] && quantityArray[i] > 1 && ! varietyArray[i]) {
            document.getElementById("cartslot-"+j+"-qty").style.backgroundImage = "url(images/qtyr-"+quantityArray[i]+".gif)";
        } else {
            document.getElementById("cartslot-"+j+"-qty").style.backgroundImage = "url(images/spacer.gif)";
        }
      }
      
      document.getElementById("cartslot-"+j+"-block").style.display = "block";
    }
    else {
      document.getElementById("cartslot-"+j+"-block").style.display = "none";
      document.getElementById("cartslot-"+j+"-item").style.backgroundImage = "url(images/spacer.gif)";
      document.getElementById("cartslot-"+j+"-qty").style.backgroundImage = "url(images/spacer.gif)";
      document.getElementById("cartslot-"+j+"-var").style.backgroundImage = "url(images/spacer.gif)";
    }
    j++;
  }

  // cartl = new Image(20,55); cartl.src = "images/cart-leftarrow.gif";
  // cartr = new Image(20,55); cartr.src = "images/cart-rightarrow.gif";
  // cartl-dis = new Image(20,55); cartl-dis.src = "images/cart-leftarrow-dis.gif";
  // cartr-dis = new Image(20,55); cartr-dis.src = "images/cart-rightarrow-dis.gif";
  // document.images[imageToPoof].src = eval("poof"+poofCount+".src");
  // 	
  // 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("carthelp").style.visibility = "visible";
      document.getElementById("cartcontents").style.visibility = "hidden";
      document.getElementById("carthelp2").style.visibility = "hidden";
    }
    else {
      document.all["carthelp"].style.visibility = "visible";
      document.all["cartcontents"].style.visibility = "hidden";
      document.all["carthelp2"].style.visibility = "hidden";
    }
  }
  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);
  }
}
// READ COOKIE setup the cart when the pages lodes
function initializeCart() {
  // Get the individal cookies, if they exist
  if (getCookie("PG_REQUIRED_o")) { orderedArray  = getCookie("PG_REQUIRED_o").split(","); }
  if (getCookie("PG_REQUIRED_v")) { varietyArray  = getCookie("PG_REQUIRED_v").split(","); } 
  if (getCookie("PG_REQUIRED_q")) { quantityArray = getCookie("PG_REQUIRED_q").split(","); }
  if (getCookie("PG_REQUIRED_i")) { orderedImgArray  = getCookie("PG_REQUIRED_i").split(","); }

  // If we got stuff, redraw the cart
  if (orderedArray.length > 0) {
    displayCartThumbs(cartScroll);
    displayTotalPrice();
  }
}

// SET COOKIE install the current cart in the browser cookie

function setCartCookie() {
  document.cookie = "PG_REQUIRED_o="+escape(orderedArray)+"; path=/; domain=."+location.host;
  document.cookie = "PG_REQUIRED_v="+escape(varietyArray)+"; path=/; domain=."+location.host;
  document.cookie = "PG_REQUIRED_q="+escape(quantityArray)+"; path=/; domain=."+location.host;
  document.cookie = "PG_REQUIRED_i="+escape(orderedImgArray)+"; path=/; domain=."+location.host;
}

// UTIL: Get a single cookie
// Source: http://www.netspade.com/articles/javascript/cookies.xml

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

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

var cartLayer = "cart";
var dragLayer = "ItemDrag";
var dragImage = "DragImage";
var highlightElement = "cart-main";
var removeElementdiv="binBox";

// ROLLOVER - Layer capable rollover function

function hiLite(imgDocID, imgObjName, imgLayerID) {
	//alert(imgObjName);
  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) {
   // alert("Here");
   if (isStd) {
     theObj = document.getElementById(what);
     if (theObj.style.visibility == "hidden" || theObj.style.visibility == "") {
       theObj.style.visibility = "visible";
     } else {
       theObj.style.visibility = "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";
     }
   }
}

// 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;
		//alert(xWin +" ; "+ yWin);
  }
  else {
    theTarget = window.event.srcElement;
    xWin = window.event.clientX;
    yWin = window.event.clientY + document.documentElement.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
  // "product_images/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!");
    }
    else 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("-"));
			itemImg = theTarget.src;
			imgWd = theTarget.width;
			imgHt = theTarget.height;
      //alert(itemName)
      // However, if it's a dynamic shopping cart thumb, get it from the array      
      if (itemName.indexOf("cartslot") != -1) {//alert(itemName);
        // Determine which thumb was chosen, add the scroll offset to get the item name
				itemObj = document.getElementById(itemName+"-item");
				itemImg = itemObj.style.backgroundImage;
				itemImg = itemImg.substring(4,itemImg.length-1);
      	itemCartSlot = theTarget.name.substring(theTarget.name.indexOf("-") + 1, theTarget.name.lastIndexOf("-"));
      	itemName = orderedArray[parseInt(itemCartSlot) + parseInt(cartScroll)];		
      }
    //alert(itemImg);
	  // 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);
				//theLayer.style.left=10;
        //alert("Layer: " + layerClicked + " Object: " + theLayer + " Left: " + theLayer.style.left);
      }
            
      // 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
        // Also get half the width and the height of the image being dragged, for layer calcuations.
 			//alert(dragImage);
        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(itemImg) == -1) {
              document.images[dragImage].src = itemImg;							
            }
						document.images[dragImage].width = imgWd;
						document.images[dragImage].height = imgHt;						
          }
          else {
            if (document.images[dragImage].src.indexOf(itemImg) == -1) {
              document.images[dragImage].src = itemImg;
            }
						document.images[dragImage].width = imgWd;
						document.images[dragImage].height = imgHt;
          }
        }
        if (isStd) {
          theObj = document.getElementById(dragImage);
          if (theObj.getAttribute("src") != itemImg) {
            theObj.setAttribute("src", itemImg);
          }

          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!
					//alert(theTarget.width);
					theObj.setAttribute("width", imgWd+"px");
					theObj.setAttribute("height", imgHt+"px");
          //theLayer.style.height = (theTarget.height)+"px";
		  
          theLayer.style.left = (xWin - 20)+"px";
          theLayer.style.top = (yWin - 20)+"px";
        }

        // 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) - dragImageHeight;
      		  snapStartX = document.all[layerClicked].style.pixelLeft;
      		  snapStartY = document.all[layerClicked].style.pixelTop;
      	}
    	}             
        dropperHighlight = 0;
        removeHighlight = 0;
        layerShowing = "false";
        
				document.onmousemove = drag;	     
        return false;
      }
    }
  }
}

function moveLayer(e){
	if (isStd) {
		// Nav6: Track the difference, and add the starting position to it  
		theLayer.style.left = (startX + e.clientX - oldX)+"px";
		theLayer.style.top = (startY + e.clientY - oldY)+"px";
		// 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.documentElement.scrollTop - dragImageHeight;
		}
	}
}

// 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);
       layerShowing = "true";
    }
     
    // Now, actually move the layer    
    moveLayer(e);
    
    // 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;
    }
    
    // Now, get the area of the drop layer, accounting for any amount of scroll    
    if (isStd) {
      dropID = document.getElementById(cartLayer);
      dropperY = dropID.offsetTop + document.documentElement.scrollTop;
			dropperX = dropID.offsetLeft + document.documentElement.scrollLeft;
			binID = document.getElementById('binBox');
      binY = binID.offsetTop + document.documentElement.scrollTop;
			binX = binID.offsetLeft + document.documentElement.scrollLeft;
    }
    if (isIE) {
      dropID = document.getElementById(cartLayer);
      dropperY = dropID.offsetTop;  
			dropperX = dropID.offsetLeft;
			binID = document.getElementById('binBox');
      binY = binID.offsetTop;  
			binX = binID.offsetLeft;
    
		// window.status = "Drag! " + currentX + "/" + currentY + " - " + dropperY + " - " + dropID.offsetTop;
		}
		dropperWd = dropID.offsetWidth;
		dropperHt = dropID.offsetHeight;
		binWd = binID.offsetWidth;
		binHt = binID.offsetHeight;
   //alert(dropperWd+" ; "+dropperHt)
	 //alert(binWd+" ; "+binHt);
	
    // 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...
					removeOccured = 1;
					 
					// Now make this slot temporarily "dissapear" and slide it out by shrinking its width	
					document.getElementById("cartslot-"+itemCartSlot+"-item").style.visibility = "hidden";
					document.getElementById("cartslot-"+itemCartSlot+"-qty").style.visibility = "hidden";
					document.getElementById("cartslot-"+itemCartSlot+"-var").style.visibility = "hidden";
			if ( (currentY < dropperY || currentX < dropperX || currentY > (dropperY+dropperHt) || currentX > (dropperX+dropperWd)) ){				
				//&& 
			//if (	(currentY > binY && currentY < (binY+binHt) && currentX > binX && currentX < (binX+binWd)) ){ 			
			// 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;					
					
					/*if (currentlyResizingFlag != 1 && rightScrollAct == 0 && leftScrollAct == 0) {
						//resizeTimer = setInterval("resizeWidthElement('cartslot-"+itemCartSlot+"-block', 0, -5)", 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+"-block', cartSlotSize, 5)", 25);
					}*/
				}
   		}
			
   } else {
      // IN - We're dragging an item INTO the cart
			if (currentY > dropperY && currentX > dropperX && currentY < (dropperY+dropperHt) && currentX < (dropperX+dropperWd)) {
      //if (currentY > dropperY) {
				// The mouse is in, so highlight!

				dropperHighlight = 1;
				hiElem = document.getElementById(highlightElement);
				hiElem.style.backgroundColor = '#cfebfc';
			}
			else {
				dropperHighlight = 0;
				hiElem = document.getElementById(highlightElement);
				hiElem.style.backgroundColor = '#ffffff';
			}
		}  
		
		if(removeHighlight==1)
		{
			if (currentY > binY && currentX > binX && currentY < (binY+binHt) && currentX < (binX+binWd)) {
    	  //if (currentY > dropperY) {
				// The mouse is in, so highlight!
				remElemdiv = document.getElementById(removeElementdiv);
				remElemdiv.style.backgroundImage='url(images/drag_ho.jpg)';
			}
			else {				
				remElemdiv = document.getElementById(removeElementdiv);
				remElemdiv.style.backgroundImage='url(images/drag.jpg)';
			}
		}
		
    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);
         }
         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);
         }
         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? 
		
    remElemdiv = document.getElementById(removeElementdiv);
		remElemdiv.style.backgroundImage='url(images/drag.jpg)';
		if (dropperHighlight == 1) {	
        // ADD THE THING TO THE CART HERE						
				if(document.getElementById('prodQty')){
					itemQty=parseInt(document.getElementById('prodQty').value);
					//if(isEmpty())
					addToCart(itemName,itemQty);
					/*for(ad=0;ad<document.getElementById('prodQty').value;ad++){
						if(isEmpty())
						addToCart(itemName,1);
						else
						break;
					}*/
				}else	{	
					//if(isEmpty())
					addToCart(itemName,1);
				}
        // Clear everything out			
        dropperHighlight = 0;	
        hiElem = document.getElementById(highlightElement);
        hiElem.style.backgroundColor = '#ffffff';
	  		
        toggleVisibility(layerClicked);
	  	
        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)", 125);
			
			remElemdiv = document.getElementById(removeElementdiv);
			remElemdiv.style.backgroundImage='url(images/drag.jpg)';
			
			// Show the cart slot layer again (since it was likely hidden during the drag out)
			document.getElementById("cartslot-"+itemCartSlot+"-block").style.width = cartSlotSize;
			document.getElementById("cartslot-"+itemCartSlot+"-item").style.visibility = "visible";
			document.getElementById("cartslot-"+itemCartSlot+"-qty").style.visibility = "visible";
			document.getElementById("cartslot-"+itemCartSlot+"-var").style.visibility = "visible";

			// REMOVE THE ITEM FROM THE CART		
			removeFromCart(itemCartSlot);
			removeHighlight = 0;
    }    
    // If not, animate "snapping back", buy 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 (removeOccured == 1) {				
				document.getElementById("cartslot-"+itemCartSlot+"-block").style.width = cartSlotSize;
				document.getElementById("cartslot-"+itemCartSlot+"-item").style.visibility = "visible";
				document.getElementById("cartslot-"+itemCartSlot+"-qty").style.visibility = "visible";
				document.getElementById("cartslot-"+itemCartSlot+"-var").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+"px";
     document.getElementById(layerToSnap).style.top = snapY+"px";
   }
   else {
      document.all[layerToSnap].style.pixelLeft = snapX;
      document.all[layerToSnap].style.pixelTop = snapY;
   }
   
   if (snapCurrent == steps) {
     clearInterval(snapTimer);
     // window.status = "Snap complete.";
     toggleVisibility(layerToSnap);
     layerShowing = "false";
     movingStatus = "false";
		 if (document.getElementById("cartslot-"+itemCartSlot+"-block")) {				
				document.getElementById("cartslot-"+itemCartSlot+"-block").style.width = cartSlotSize;
				document.getElementById("cartslot-"+itemCartSlot+"-item").style.visibility = "visible";
				document.getElementById("cartslot-"+itemCartSlot+"-qty").style.visibility = "visible";
				document.getElementById("cartslot-"+itemCartSlot+"-var").style.visibility = "visible";
      }
   }
}

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

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

function animatePoofForAll(itemSlot) {
   poofCount++;
   if (poofCount == 6) {
		 document.getElementById("cartslot-"+itemSlot+"-item").style.backgroundImage = "url(images/spacer.gif)";
     //document.images[imageToPoof].src = "images/spacer.gif";
     clearInterval(poofTimer);
   }
   else {
		 document.getElementById("cartslot-"+itemSlot+"-item").style.backgroundImage = "url("+eval("poof"+poofCount+".src");+")";
     //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;

  rszElement = document.getElementById(theID);

  // window.status = "Current: "+rszElement.style.width+ " Goal: " + rszGoal + " Amount: " + rszAmount;
  if ((rszAmount < 0 && (parseFloat(rszElement.style.width) + rszAmount) <= rszGoal) || (rszAmount > 0 && (parseFloat(rszElement.style.width) + rszAmount) >= rszGoal)) {
    rszElement.style.width = rszGoal+"px";
    clearInterval(resizeTimer);
    currentlyResizingFlag = 0;
    // window.status = "RESIZE DONE";
  } else {
    rszElement.style.width = parseFloat(rszElement.style.width) + rszAmount+"px";
  }
}

function isEmpty(){
	if (orderedArray.length >= cartSpaces) {
		//alert("The maximum limit has reached.\nYou cannot add more items in the box");
		document.getElementById("divpopupmsg").innerHTML="Sorry, but you’ve reached the maximum number of drinks ("+cartSpaces+") for a box."
		TB_show("Maximum Drinks Reached","#TB_inline?height=100&amp;width=300&amp;inlineId=divpopupmsg",'');
		return false;
	}else
	return true;
}

// 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;

 
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}
