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

var cartLayer = "tray";
var dragLayer = "ItemDrag";
var dragImage = "DragImage";
var oldX, oldY, movingStatus, layerClicked, what, clickURL, helpUp;

function toggleVisibility(what) {

  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";
    }
  }
}

function doDown(e) {

  if (movingStatus == "drag") {
    return;
  }

  // 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 id of what we've clicked, and initialize a drag if it is a choice div (ends by "-choice")

  if (theTarget.id.indexOf("-choice") != -1) {

    // Clear some things just in case  
    itemName = "";
    layerClicked = "";
    theLayer = "";
    
    // Get the itemname from the image 'name' tag, in 95% of the cases    
    itemName = theTarget.id.substring(0,theTarget.id.lastIndexOf("-"));
          
    // 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) {

      theTarget.style.visibility = "hidden";

      // 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 (document.images[dragImage].src.indexOf("/images/pack/"+itemName+"_drag.gif") == -1) {
          document.images[dragImage].src = "/images/pack/"+itemName+"_drag.gif" ;
        }
      }
      else if (isStd) {
        theObj = document.getElementById(dragImage);
        if (theObj.getAttribute("src") != "/images/pack/"+itemName+"_drag.gif") {
          theObj.setAttribute("src", "/images/pack/"+itemName+"_drag.gif");
        }

        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!

        x = xWin - dragImageWidth;
        y = yWin - dragImageHeight;
        theLayer.style.left = x + 'px';
        theLayer.style.top = y + '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.clientX; // was offset!
        oldY = window.event.clientY;

      }
                      
      // 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 {
          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;
      }    
      isInTray = 0;
      layerShowing = "false";
      document.onmousemove = drag;	     
      return false;
    }
  }
}

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  
      x = startX + e.clientX - oldX;
      y = startY + e.clientY - oldY;
      theLayer.style.left = x + 'px';
      theLayer.style.top = y + '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 {

      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;

    }
    
    // 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;
    
    if (currentY > dropperY) {
      idx = getAvailableSlotIndex();
      if (idx > -1) {
        slot = document.getElementById(slot_array[idx]);
        //slot.style.backgroundPositionY = '-108px';
        slot.style.backgroundPosition = '0px -108px';
      }
      
      isInTray = 1;
    }
    else {
      idx = getAvailableSlotIndex();
      if (idx > -1) {
        slot = document.getElementById(slot_array[idx]);
        //slot.style.backgroundPositionY = '0px';
        slot.style.backgroundPosition = '0px 0px';
      }

      isInTray = 0;
    }
             
    return false;
  }
}

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) {

      //if (oldX == e.clientX && oldY == e.clientY) {
      if ((Math.abs(oldX - e.clientX) <= 50) && (Math.abs(oldY - e.clientY) <= 50)) {
        // Turn off the drag layer        
        if (layerShowing == "true") {
          layerShowing = "false";
          toggleVisibility(layerClicked);
        }
        movingStatus = "false";
        document.onmousemove = null;        
        theTarget.style.visibility = "visible";
        return false;
      }
    }
    else {

      if ((Math.abs(oldX - window.event.clientX) <= 50) && (Math.abs(oldY - window.event.clientY) <= 50)) {
        if (layerShowing == "true") {
          layerShowing = "false";
          toggleVisibility(layerClicked);
        }
        movingStatus = "false";
        document.onmousemove = null;
        theTarget.style.visibility = "visible";
        return false;
      } 

    } 
  
    // Drag has ended. Tear down events and such.
    document.onmousemove = null;
    
    // Did the icon reach any drag target?
    target_index = getAvailableSlotIndex();
    if (isInTray == 1 && target_index != -1) {

      addToTray(theTarget, layerClicked, target_index);

      // Clear everything out			
      isInTray = 0;	

    } else {
    // If not, animate "snapping back", buy only if the DIV actually moved!    
      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);
      }
    }
    
    return false;
  }
}

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

    theTarget.style.visibility = "visible";
  }
}

function addToTray(targ, layerClicked, target_index) {
  img = document.getElementById(dragImage);
  slot = document.getElementById(slot_array[target_index]);
  //slot.style.backgroundPositionY = '0px';
  slot.style.backgroundPosition = '0px 0px';
  rem_img = img.src.replace(/(.*\/)(\w+)_drag[.](.+)$/, '$1$2_remove.$3');                       
  slot.style.backgroundImage = "url(" + rem_img + ")";
  toggleVisibility(layerClicked);
  layerShowing = "false";
  movingStatus = "false";
  choice_array[target_index] = targ.id;
  targ_label = targ.id.match(/[^-]+/);
  setSessionVar('tray_content', target_index + ':' + targ_label);    
}

function getAvailableSlotIndex() {

  if (!window.slot_array) {
    alert('ERREUR : slot_array n\'est pas defini!');
    return -1;
  } else if (!window.limit_array) {
    alert('ERREUR : limit_array n\'est pas defini!');
  }
  for (i = limit_array[0]; i <= limit_array[1]; i++) {
    if (document.getElementById(slot_array[i]).style.backgroundImage == "")
      return i;
  }
  return -1;
}

function doClick(e) {

  // Calculate the mouse's click position
  if (isStd) {
    targ = e.target;
  } else {
    targ = window.event.srcElement;
  }

  if (targ.id.indexOf("-position") != -1) {
    if (targ.style.backgroundImage.indexOf('remove') != -1) {
      idx = -1;
      for (i = limit_array[0]; i <= limit_array[1]; i++) { 
        //alert(choice_array[i]);
        if (slot_array[i] == targ.id) {
          idx = i;
          break;
        }
      }
      if (idx == -1)
        alert('erreur js dans doclick()');

      targ.style.backgroundImage = '';
      document.getElementById(choice_array[idx]).style.visibility = "visible";
      choice_array[idx] = '';

      setSessionVar('tray_content', idx + ':' + '')
    }
  }

}

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

///////////////////////
// AJAX STUFF
///////////////////////

function createRequestObject() {    
  if (isIE) {
    ro = new ActiveXObject("Microsoft.XMLHTTP");    
  }else{        
    ro = new XMLHttpRequest();    
  }    
  return ro;
}

var http_set = createRequestObject();
var http_get = createRequestObject();
var http_setiffnotset = createRequestObject();
var http_updatetray = createRequestObject();

function setSessionVar(vr, vl) {
  http_set.open('get', 'ajax_session.php?var=' + vr + '&val=' + vl); 
  http_set.onreadystatechange = handleSetSessionVarResponse;	    
  http_set.send(null);
}

function handleSetSessionVarResponse() {    
  if(http_set.readyState == 4) {        
    //alert('Set : ' + http_set.responseText);
  }
}

function getSessionVar(vr) {
  http_get.open('get', 'ajax_session.php?var=' + vr); 
  http_get.onreadystatechange = handleGetSessionVarResponse;	    
  http_get.send(null);
}

function handleGetSessionVarResponse() {    
  if(http_get.readyState == 4) {        
    alert('Get : ' + http_get.responseText);
  }
}

function setIffNotSetSessionVar(vr, vl) {
  http_setiffnotset.open('get', 'ajax_session.php?var=' + vr + '&val=' + vl + '&setiffnotset'); 
  http_setiffnotset.onreadystatechange = handleSetIffNotSetSessionVarResponse;
  http_setiffnotset.send(null);
}

function handleSetIffNotSetSessionVarResponse() {
  if(http_setiffnotset.readyState == 4) {        
    //alert('SetIffNotSet : ' + http_setiffnotset.responseText);
  }
}

function updateTray() {
  http_updatetray.open('get', 'ajax_session.php?var=' + 'tray_content'); 
  http_updatetray.onreadystatechange = handleUpdateTrayResponse;	    
  http_updatetray.send(null);  
}

function handleUpdateTrayResponse() {    
  if(http_updatetray.readyState == 4) {        
    //alert(http_updatetray.responseText);
    tokens = http_updatetray.responseText.split(' ');

    if ((tokens.length - 1) != slot_array.length) {
      //alert('erreur dans handleUpdateTrayResponse() : tokens.len != slot_array.len\nAjax answer = ' + http_updatetray.responseText);
      return;
    }

    for (i = 0; i < tokens.length; i++) {
      if (tokens[i] != '') {
        tt = tokens[i].split(':');

        if (tt.length != 2) {
          //alert('erreur dans handleUpdateTrayResponse() : tt.len != 2\nAjax answer = ' + http_updatetray.responseText);
          return;
        }

        if (/\d+/.test(tt[0]) == false) {
          //alert('erreur dans handleUpdateTrayResponse() : tt[0] is not numeric\nAjax answer = ' + http_updatetray.responseText);
          return;
        }

        if (tt[1] != '') {

          slot = document.getElementById(slot_array[tt[0]]);
          image_state = '_drag';
          if (tt[0] >= limit_array[0] && tt[0] <= limit_array[1]) {
            image_state = '_remove';
            choice = document.getElementById(tt[1] + '-choice');
            choice.style.visibility = 'hidden';
          }
          img_url = '/images/pack/' + tt[1] + image_state + '.gif';
          slot.style.backgroundImage = "url(" + img_url + ")";          

          choice_array[tt[0]] = tt[1] + '-choice';
          //alert(slot.style.backgroundPosition);
        }
      }
    }
  }
}

////////////////////////////////////////////////////////////////

// next button validation
function checkNext(erreur_id) {
  ok = false;
  for (i = limit_array[0]; i <= limit_array[1]; i++) {
    if (choice_array[i] && choice_array[i] != '') {
      //alert(choice_array[i]);
      ok = true;
    }
  }
  
  if (ok) {
    return true;
  } else {
    document.getElementById(erreur_id).style.display = 'block';
    return false;
  }
}
