/*
  All code (javascript/html/css) Copyright 2005 Jonathan Baudanza
  All rights reserved
*/
// If an object is being dragged, this will reference it.
// If no object is being dragged, this will be a null reference.
var dragMe;

// Reference to the coordinates where dragMe was grabbed
var grabbed;

var iconHeight;
var iconWidth;

// total size of the shaded viewport
var viewportWidth =  470;
var viewportHeight = 200;

// The distance between the edge of the viewport and the start of the
// cropping square
var marginY;
var marginX;

// Coordinates of the center of the viewport
var viewportCenterX;
var viewportCenterY;

var zoomBar;

function sizeChange()
{
  var size = document.getElementById( 'sizeSelect' ).value.split( 'x' );
  document.getElementById( 'sizes' ).value = size[0];
  setIconSize( parseInt(size[0]), parseInt(size[1]) );
  setupViewport();
  
}

function setIconSize( width, height)
{
  iconWidth = width;
  iconHeight = height;

  // The distance between the edge of the viewport and the start of the
  // cropping square
  marginY = (viewportHeight - iconHeight) / 2;
  marginX = (viewportWidth - iconWidth) / 2;

  // Coordinates of the center of the viewport
  viewportCenterX = viewportWidth / 2;
  viewportCenterY = viewportHeight / 2;
}

var w = parseInt( getQueryArg( 'iconWidth' ) );
var h = parseInt( getQueryArg( 'iconHeight' ) );
setIconSize( w?w:80, h?h:80 );

function debugText( string )
{
  var form = document.getElementById( 'debugForm' );
  form.debugtext.value += string + "\n";
}

function myMouseMove( event )
{
  if( !event )
  { event = window.event; }

  if( !dragMe )
    return;
    
  var style = dragMe.style;

  if( dragMe.hdrag )
  {
    var pos = event.clientX - grabbed.clientX;

    if( dragMe.hdragmax && pos >= dragMe.hdragmax )
      pos = dragMe.hdragmax;
      
    if( dragMe.hdragmin && pos <= dragMe.hdragmin )
      pos = dragMe.hdragmin;
    
    // XXX: IE was puking on this
    style.left = pos + "px";
  }

  if( dragMe.vdrag )
  {
    var pos = event.clientY - grabbed.clientY;

    if( dragMe.vdragmax && pos >= dragMe.vdragmax )
      pos = dragMe.vdragmax;
      
    if( dragMe.vdragmin && pos <= dragMe.vdragmin )
      pos = dragMe.vdragmin;
      
    style.top = pos + "px";
  }

  if( dragMe.onPositionChange )
  {
    dragMe.onPositionChange();
  }

  return false;
}

function myMouseUp( event )
{
  dragMe = null;
  grabbed = null;
  return false;
}

function myMouseDown( event )
{
  if( !dragMe )
    return true;

  var style = dragMe.style;
  grabbed = new Object;

  if( !event )
  { event = window.event; }
  
  grabbed.clientX = event.clientX;
  if( style.left )
  {
    // XXX: assert that these are in px
    grabbed.clientX -= parseInt( style.left );
  }

  grabbed.clientY = event.clientY;
  if( style.top )
  {
    // XXX: assert that these are in px
    grabbed.clientY -= parseInt( style.top );
  }

  return false;
}

// Calculates image.zoomX and image.zoomY.  These are the coordinates of the
// center of the image when it is scaled to 1.
function setZoomPos()
{
  var image = document.getElementById( 'iconImage' );
  var x = parseInt( image.style.left );
  var y = parseInt( image.style.top );

  var centerX = viewportCenterX - x;
  image.zoomX = centerX * image.origWidth / image.width;

  var centerY = viewportCenterY - y;
  image.zoomY = centerY * image.origHeight / image.height;
}

// If val is less than min, min is returned
// If val is less than max, max is returned.
// Otherwise, val is returned
function constrain( val, min, max )
{
  if( val > max )
    return max;
  else if( val < min )
    return min;
  else
    return val;
}

function setScale( scale )
{
  if( !scale )
    return;

  var image = document.getElementById( 'iconImage' );
  var style = image.style;

  // Figure out what the center is in the current scale
  var centerX = image.zoomX * scale;
  var centerY = image.zoomY * scale;

  style.left = (viewportCenterX - centerX) + "px";
  style.top = (viewportCenterY - centerY) + "px";
  
  // Do the actual scaling work
  image.width = image.origWidth * scale;
  image.height = image.origHeight * scale;

  // Set some the dragging boundaries
  var buffer = 10;
  image.hdragmax = viewportWidth - buffer;
  image.vdragmax = viewportHeight - buffer;
  image.hdragmin = buffer - image.width;
  image.vdragmin = buffer - image.height;

  // Make sure the image wasn't zoomed off of the view
  image.style.left = constrain( parseInt( image.style.left ), image.hdragmin, image.hdragmax ) + "px";
  image.style.top = constrain( parseInt( image.style.top ), image.vdragmin, image.vdragmax ) + "px";
}

function setInitialScale()
{
  var image = document.getElementById( 'iconImage' );

  // If there is an imageWidth in the query arg, then
  // scale the image appropriately
  var imageWidth = getQueryArg( 'imageWidth' );
  
  // Otherwise, scale the image to the size of the editor window
  if( !imageWidth )
  {
    imageWidth = viewportWidth;
  }
  
  zoomBar.setPosition( imageWidth / image.origWidth );
}

function startImageDrag()
{
  dragMe = document.getElementById( 'iconImage' );
}

function centerImage()
{
  var image = document.getElementById( 'iconImage' );

  image.style.left = ((viewportWidth - image.width) /2 ) + "px";
  image.style.top = ((viewportHeight - image.height) /2 ) + "px";
}

function setGeometry( id, x, y, width, height )
{
  var obj = document.getElementById( id );
  obj.style.left = x + "px";
  obj.style.top = y + "px";
  if( width )
  {
    obj.style.width = width + "px";
  }

  if( height )
  { 
    obj.style.height = height + "px";
  }
  return obj;
}

function loadGuuid( guuid )
{
  var image = document.createElement( 'img' );
  image.id = 'iconImage';
  
  // Enable dragging
  image.vdrag = true;
  image.hdrag = true;
  image.style.position = "relative";
  image.onPositionChange = setZoomPos;
  image.onmousedown = startImageDrag;

  if( guuid )
  {  
    // Pull the original geometry from the query args
    var origWidth = getQueryArg( 'origWidth' );
    if( origWidth )
    {
      image.width = image.origWidth = origWidth;
    }
    var origHeight = getQueryArg( 'origHeight' );
    if( origHeight )
    {
      image.height = image.origHeight = origHeight;
    }
    image.src = imageDir + guuid;			//edited by si - 19/06/06
  }
  else
  {
    // XXX: Magic number
    image.width = image.origWidth = 80;
    image.height = image.origHeight = 80;
    image.src='images/default.jpg';
  }

  // Add the image to the DOM
  document.getElementById( 'clipper' ).appendChild( image );

  // Make sure <select> element matches the icon size
  var options = document.getElementById( 'sizeSelect' ).options;
  var value = iconWidth + "x" + iconHeight;
  for( i=0; i<options.length; i++ )
  {
    options[i].selected = ( options[i].value == value );
  }

  return image;
}

function setupViewport()
{  
  // Configure shading
  setGeometry( 'shadingTop', 0, 0, viewportWidth, marginY );
  setGeometry( 'shadingBottom', 0, marginY+iconHeight, viewportWidth, marginY );
  setGeometry( 'shadingLeft', 0, marginY, marginX, iconHeight );
  setGeometry( 'shadingRight', marginX + iconWidth, marginY, marginX, iconHeight );
  
  setGeometry( 'clipper', 0, 0, viewportWidth, viewportHeight );
  setGeometry( 'editor', 0, 0, viewportWidth, viewportHeight + 15 );
}

// This is a kludge to get the opacity layer to work in browsers that 
// don't support .opacity or .filter (such as opera).
// This is done by tiling an transparent PNG across the div
function opacityKludge( id )
{
  var style = document.getElementById( id ).style;
  
  if( style.opacity == undefined && style.filter == undefined )
  {
    style.backgroundColor = 'transparent';
    style.backgroundImage = 'url("t60.png")';
    style.backgroundRepeat = 'repeat';
  }
}

function setupPositions()
{
  // 'editor' wraps the clipper and the scrollbar
  obj = document.getElementById( 'editor' );
  obj.style.height = ( viewportHeight + 50 ) + "px"
  
  setupViewport();

  var image = loadGuuid( getQueryArg( 'guuid' ) + '.' + getQueryArg( 'ImgType' ) );		//edited by si - 19/06/06

  // Determine the smallest this image will scale
  var minWidth = image.origWidth ? iconWidth / image.origWidth : 1.0;
  var minHeight = image.origHeight ? iconHeight / image.origHeight : 1.0;
  image.minScale = Math.min(minWidth, minHeight);
  
  zoomBar = createZoomBar( 0, 0, 258, 20 );
  zoomBar.onPositionChange = setScale;
  zoomBar.minVal = image.minScale;
  zoomBar.maxVal = 2;

  // Position the zoomBar below the editor
  document.getElementById( 'content' ).insertBefore( zoomBar, document.getElementById( 'editor' ).nextSibling );

  centerImage();

  setZoomPos();

  setInitialScale();

  // If a position was passed in the query args, then
  // position the image appropriately
  var xPos = getQueryArg( 'xPos' );
  var yPos = getQueryArg( 'yPos' );
  if( xPos != null && yPos != null )
  {
    setGeometry( 'iconImage', marginX - xPos, marginY - yPos, null, null );
    setZoomPos();
  }

  opacityKludge( 'shadingTop' );
  opacityKludge( 'shadingBottom' );
  opacityKludge( 'shadingLeft' );
  opacityKludge( 'shadingRight' );
  zoomBar.setPosition('1');
}

// Populates an object with the attributes needed to perform a render op
function getRenderAttributes()
{
  var obj = new Object();

  var guuid = getQueryArg( 'guuid' );
  obj.guuid = guuid ? guuid : '';

  var image = document.getElementById( 'iconImage' );

  obj.origWidth = image.origWidth;
  obj.origHeight = image.origHeight;
  
  var image = document.getElementById( 'iconImage' );
  var style = image.style;

  obj.xPos = marginX - parseInt( style.left );
  obj.yPos = marginY - parseInt( style.top );

  // Set the size of the scalled image
  obj.imageWidth = image.width;
  obj.imageHeight = image.height;
  
  // Set the size of the output icon
  obj.iconWidth = iconWidth;
  obj.iconHeight = iconHeight;

  return obj;
}

// Prepare the hidden form values for submitting
function onRenderFormSubmit( form )
{
  var atts = getRenderAttributes();

  for( a in atts )
  {
    form[a].value = atts[a];
  }
}

function showMessage( id )
{
    var msg = getQueryArg( id );
    if( msg )
    {
      document.write( '<div id="' + id + '">' + unescape(msg) + '</div>' );
    }
}

// XXX: If the mouse is released outside the browser, we never
// get the mouseUp event
document.onmousemove = myMouseMove;
document.onmouseup  = myMouseUp;
document.onmousedown = myMouseDown;
