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";
}

////////////////
//
// DRAGGING / DROPPING related code
//
////////////////

var cartLayer = "cart";
var dragLayer = "ItemDrag";
var dragImage = "DragImage";
var highlightElement = "cart-main";

// 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) {

   // 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;
  }
  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);
      }
            
      // 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-items/"+itemName+"/drag.png") == -1) {
              document.images[dragImage].src = "images-items/"+itemName+"/drag.png";
            }
          }
          else {
            if (document.images[dragImage].src.indexOf("images-items/"+itemName+"/drag.gif") == -1) {
              document.images[dragImage].src = "images-items/"+itemName+"/drag.gif";
            }
          }
        }
        if (isStd) {
          theObj = document.getElementById(dragImage);
          if (theObj.getAttribute("src") != "images-items/"+itemName+"/drag.png") {
            theObj.setAttribute("src", "images-items/"+itemName+"/drag.png");
          }

          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) - dragImageHeight;
      		  snapStartX = document.all[layerClicked].style.pixelLeft;
      		  snapStartY = document.all[layerClicked].style.pixelTop;
      		}
    	}    
         
        dropperHighlight = 0;
        removeHighlight = 0;
        layerShowing = "false";
         
		document.onmousemove = drag;
	     
        return 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);
       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;
    }
    
    // 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";
		  document.getElementById("cartslot-"+itemCartSlot+"-qty").style.visibility = "hidden";
		  document.getElementById("cartslot-"+itemCartSlot+"-var").style.visibility = "hidden";
		  if (currentlyResizingFlag != 1 && rightScrollAct == 0 && leftScrollAct == 0) {
		    resizeTimer = setInterval("resizeWidthElement('cartslot-"+itemCartSlot+"-block', 1, -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+"-block', 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.backgroundColor = '#cfebfc';
	  }
	  else {
		dropperHighlight = 0;
		hiElem = document.getElementById(highlightElement);
		hiElem.style.backgroundColor = '#edf8ff';
      }
    }
             
    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?
    
    if (dropperHighlight == 1) {
	
        // ADD THE THING TO THE CART HERE
		
        addToCart(itemName);

        // Clear everything out
			
        dropperHighlight = 0;	
        hiElem = document.getElementById(highlightElement);
        hiElem.style.backgroundColor = '#edf8ff';
	  	
        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)", 75);

        // 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;
     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);
     layerShowing = "false";
     movingStatus = "false";
   }
}

// 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");
   }
}

// 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;
    clearInterval(resizeTimer);
    currentlyResizingFlag = 0;
    // window.status = "RESIZE DONE";
  } else {
    rszElement.style.width = parseFloat(rszElement.style.width) + rszAmount;
  }
}

// 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;

