// scales the image, repositions in the center, checks the bounds of the draggable image, if out of bounds, prevents dragging
function scaleNode(node, scale) {
  //get handle on ghost of this node
  var ghostNode = getGhostNode(node);

  if (!node || !ghostNode) {
    return true;
  }

  var clipWidth = ghostNode.getWidth() + "px";
  var clipHeight = ghostNode.getHeight + "px";
  var aspectRatio = parseInt(clipHeight) / parseInt(clipWidth);  //aspect ratio

  var centerpoint_x = parseInt(node.style.left) + Math.floor(parseInt(node.style.width)/2);
  var centerpoint_y = parseInt(node.style.top) + Math.floor(parseInt(node.style.height)/2);

  //scale the image
  node.style.width = Math.floor(parseInt(node.originalWidth) * scale) + 'px';
  node.style.height = Math.floor(parseInt(node.originalHeight) * scale) + 'px';


  //reposition image so its centered
  //find center x coordinate of image
  var newPosX = centerpoint_x - Math.floor(parseInt(node.style.width) / 2) + "px";
  var dx = parseInt(node.style.left) - parseInt(newPosX);  //difference between new and old position
  node.style.left = newPosX;

  //find center y coordinate of image
  var newPosY = centerpoint_y - Math.floor(parseInt(node.style.height) / 2) + "px";
  var dy = parseInt(node.style.top) - parseInt(newPosY);  //difference between new and old position
  node.style.top = newPosY;


  //check the bounds of the draggable image
  //if out of bounds, prevent dragging
  var over = checkDragBounds(node);
  //images that are smaller than the clipping area can be moved around inside it
  var isSmallY = (node.getWidth() < ghostNode.getWidth());
  var isSmallX = (node.getHeight() < ghostNode.getHeight());
  var operatorX = (isSmallY) ? "<" : ">";  //comparison operator
  var operatorY = (isSmallX) ? "<" : ">";  //comparison operator
  if (eval(over.left + operatorX + 0)) {
    alignNodes(node, ghostNode, 'left');
  }
  else if (eval(over.right + operatorX + 0)) {
    alignNodes(node, ghostNode, 'right');
  }
  if (eval(over.top + operatorY + 0)) {
    alignNodes(node, ghostNode, 'top');
  }
  else if (eval(over.bottom + operatorY + 0)) {
    alignNodes(node, ghostNode, 'bottom');
  }

  updateClipping(node);  //update clip path

  //store the scale value for this node
  node.setAttribute('ms:scale', scale);
//  node.currentScale = scale;
}
//checks the bounds of the draggable image, if out of bounds, prevents dragging
function checkDragBounds(node) {
  //get handle on ghost of this node
  var ghostNode = getGhostNode(node);

  var nTop = parseInt(node.style.top);
  var nLeft = parseInt(node.style.left);
  var nBottom = nTop + node.getHeight();
  var nRight = nLeft + node.getWidth();

  var gTop = parseInt(ghostNode.style.top);
  var gLeft = parseInt(ghostNode.style.left);
  var gBottom = gTop + ghostNode.getHeight();
  var gRight = gLeft + ghostNode.getWidth();

  //return how much the node is out of the bounds of the ghost node
  var dTop = nTop - gTop;
  var dLeft = nLeft - gLeft;
  var dBottom = gBottom - nBottom;
  var dRight = gRight - nRight;

  var dObj = {
    top: dTop,
    left: dLeft,
    bottom: dBottom,
    right: dRight
  }
  return dObj;
}
// returns image's ghost node (for drag'n'drop cappabilities)
function getGhostNode(node) {
  //get handle on ghost of this node
  var ghostNodeId = GHOST_PREFIX + node.getAttribute('id');
  var ghostNode = $(ghostNodeId);
  return ghostNode;
}
// check the bounds of the draggable image and updates clipping
function translateNode(node) {
  //get handle on ghost of this node
  var ghostNode = getGhostNode(node);

  //check the bounds of the draggable image
  //if out of bounds, prevent dragging
  var over = checkDragBounds(node);
  //images that are smaller than the clipping area can be moved around inside it
  var isSmallY = (node.getWidth() < ghostNode.getWidth());
  var isSmallX = (node.getHeight() < ghostNode.getHeight());
  var operatorX = (isSmallY) ? "<" : ">";  //comparison operator
  var operatorY = (isSmallX) ? "<" : ">";  //comparison operator
  if (eval(over.left + operatorX + 0)) {
    alignNodes(node, ghostNode, 'left');
  }
  else if (eval(over.right + operatorX + 0)) {
    alignNodes(node, ghostNode, 'right');
  }
  if (eval(over.top + operatorY + 0)) {
    alignNodes(node, ghostNode, 'top');
  }
  else if (eval(over.bottom + operatorY + 0)) {
    alignNodes(node, ghostNode, 'bottom');
  }

  updateClipping(node);  //update clipping path
}
// checks image quality that the zoom isnt degrading the quality of the printed image too much
function checkImgQuality(node, scale) {
  //get handle on ghost of this node
  var ghostNode = getGhostNode(node);

  //set default min and max scale amounts
  var minScale = 1;
  var maxScale = 10;

  //check that the zoom isnt degrading the quality of the printed image too much
  var hiResWidth = node.getAttribute('ms:href-width');
  var hiResHeight = node.getAttribute('ms:href-height');
  //SAFARI BUG: getAttribute doesnt work
  if (browser.isSafari) {
    hiResWidth = extractAttributeFromNode('ms:href-width', node);
    hiResHeight = extractAttributeFromNode('ms:href-height', node);
  }
  
  if (hiResWidth && hiResHeight && hiResWidth!="" && hiResHeight!="") {
    //figure out max pixel dimension of this image
    //imgWidth(inch) * 300(pix/inch) = maxWidth(pix)
    var printWidth = hiResWidth / 72;  //convert to inches
    var htmlWidth = parseInt(node.getWidth()) / 72;
//    console.error(printWidth + "/" + htmlWidth);
  }
}
// gets difference between ghost node and real node, the clip dimensions are equal to the difference then sets the new clip area
function updateClipping(node) {
  //get handle on ghost of this node
  var ghostNode = getGhostNode(node);

  //ignore any non-draggable images
  if(!ghostNode) return;

  //get difference between ghost node and real node
  //the clip dimensions are equal to the difference
  var top = parseInt(ghostNode.style.top) - parseInt(node.style.top) + "px";
  var left =  parseInt(ghostNode.style.left) - parseInt(node.style.left) + "px";
  var right = parseInt(left) + ghostNode.getWidth() + "px";
  var bottom = parseInt(top) + ghostNode.getHeight() + "px";


  //set the new clip area
  clipNode(node, top, right, bottom, left);

}
// alligns an image by a refference node parameter
function alignNodes(node, refNode, alignment) {
  var clipDims = getClipDims(node);
  var newLeft;
  var newRight;
  switch (alignment) {
    case 'left':
      node.style.left = refNode.style.left;
      break;
    case 'right':
      node.style.left = parseInt(refNode.style.left) + refNode.getWidth() - node.getWidth() + "px";
      break;
    case 'top':
      node.style.top = refNode.style.top;
      break;
    case 'bottom':
      node.style.top = parseInt(refNode.style.top) + refNode.getHeight() - node.getHeight() + "px";
      break;      
    case 'center':
      newLeft = parseInt(refNode.style.left) + parseInt(refNode.getWidth()/2) - parseInt((node.getWidth() + clipDims.left)/2) + "px";
      node.style.left = newLeft;
      break;
    case 'middle':
      node.style.top = parseInt(refNode.style.top) + parseInt(refNode.getHeight()/2) - parseInt(node.getHeight()/2) + "px";
      break;
  }
  updateClipping(node);  //update clipping path
}
// returns clip dimmensions (top, left, right and bottom)
function getClipDims(node) {
  var clipStr = node.style.clip;
  //IE separates clip fields with spaces, not commas, so convert all commas to spaces and then apply a single regex for both browsers
  clipStr = clipStr.replace(/,/g, " ");  //replace commas with spaces to compensate for idiotic IE bug
  clipStr = clipStr.replace(/  /g, " ");  //get rid of double spaces

//  console.error(clipStr.match(/rect\((.*)\s(.*)\s(.*)\s(.*)\)/));
//  var reg = /rect\((.*),(.*),(.*),(.*)\)/;  //match svg clip path url (DOESNT WORK IN IE)
  var reg = /rect\((.*)\s(.*)\s(.*)\s(.*)\)/;  //works for IE

  var match = clipStr.match(reg);
//  var clipNodeId = match[1];  //get the id of the clip element in the svg
//console.error(match);

  var clipDims = {
    top: parseInt(match[1]),
    right: parseInt(match[2]),
    bottom: parseInt(match[3]),
    left: parseInt(match[4])
  };
  return clipDims;
}
// clips image on given parameters
function clipNode(node, top, right, bottom, left) {
    //save these as properties of the node
    node.setAttribute('clip_top', top);
    node.setAttribute('clip_left', left);
    node.setAttribute('clip_bottom', bottom);
    node.setAttribute('clip_right', right);

    //perform the clip
    var clipStr = top + ',' + right + ',' + bottom + ',' + left;

    node.style.clip = "rect(" + clipStr + ")";
//    $('debugdiv').innerHTML = "clip: " + clipStr;
}
// returns a cross-browser compatible transparent png
function createPNGNode(imgProps) {
  //this function returns a cross-browser compatible transparent png
  //if imgProps contains an oncomplete attribute, this function is called after creating the img

  var node = document.createElement('div');
  if (imgProps.id) node.id = imgProps.id;
  node.style.width = imgProps.width;
  node.style.height = imgProps.height;
  node.style.display = "block";
  
  //IE6 BUG - doesnt support PNGs. use this weird filter to display transparent PNGs correctly
  if (browser.isIE6up && (imgProps.src.substr(imgProps.src.length-4, imgProps.src.length) == ".png")) {
    node.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgProps.src + "', sizingMethod='scale')";
//IE6 BUG - onmouseover events are buggy on these kinds of png images.  so insert a transparent gif
    insertScaffoldImage(node, parseInt(imgProps.width), parseInt(imgProps.height));
  }
  //for all others, use regular img tags
  else {
    var imgNode = document.createElement('img');
    imgNode.setAttribute('src', imgProps.src);
    imgNode.style.width = imgProps.width;
    imgNode.style.height = imgProps.height;
    node.appendChild(imgNode);
  }

  var tempImg = new Image();
  tempImg.src = imgProps.src;

  Event.observe(tempImg, 'load', function(evt) {
    node.style.display = "block";
  });

  //now call the function that was passed
  if (imgProps.oncomplete) imgProps.oncomplete(node);
  
  return node;
}

