var OutlineColor = "#FF0D0D";
var PerspectiveColor = "#FFFF0D";
var divIndex = 0;

/**
 * Retrieve the coordinates of the given event relative to the center
 * of the element.
 *
 * @param event
 *   A mouse-related DOM event.
 * @param reference
 *   A DOM element whose position we want to transform the mouse coordinates to.
 * @return
 *    A hash containing keys 'x' and 'y'.
 */
function getAbsolutePosition(element)
{
  var r = { x: element.offsetLeft, y: element.offsetTop };
  if (element.offsetParent)
  {
    var tmp = getAbsolutePosition(element.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

/**
 * Retrieve the coordinates of the given event relative to the center
 * of the widget.
 *
 * @param event
 *   A mouse-related DOM event.
 * @param reference
 *   A DOM element whose position we want to transform the mouse coordinates to.
 * @return
 *    A hash containing keys 'x' and 'y'.
 */
function getRelativeCoordinates(event, reference)
{
  var x, y;
  event = event || window.event;
  var el = event.target || event.srcElement;

  if (!window.opera && typeof event.offsetX != 'undefined')
  {
    // Use offset coordinates and find common offsetParent
    var pos = { x: event.offsetX, y: event.offsetY };

    // Send the coordinates upwards through the offsetParent chain.
    var e = el;
    while (e)
    {
        e.mouseX = pos.x;
        e.mouseY = pos.y;
        pos.x += e.offsetLeft;
        pos.y += e.offsetTop;
        e = e.offsetParent;
    }

    // Look for the coordinates starting from the reference element.
    var e = reference;
    var offset = { x: 0, y: 0 }
    while (e)
    {
      if (typeof e.mouseX != 'undefined')
      {
        x = e.mouseX - offset.x;
        y = e.mouseY - offset.y;
        break;
      }
      offset.x += e.offsetLeft;
      offset.y += e.offsetTop;
      e = e.offsetParent;
    }

    // Reset stored coordinates
    e = el;
    while (e)
    {
      e.mouseX = undefined;
      e.mouseY = undefined;
      e = e.offsetParent;
    }
  }
  else
  {
    // Use absolute coordinates
    var pos = getAbsolutePosition(reference);
    x = event.pageX  - pos.x;
    y = event.pageY - pos.y;
  }
  // Subtract distance to middle
  return { x: x, y: y };
}

function MouseDown(event)
{
    // This line is to solve the issue with FireFox's drag image functionality.  This will turn off that feature.
    if (event.preventDefault) { event.preventDefault(); }
    
    mouseDown = true;
    
    // Remove event listener
    //document.getElementById("ClickDiv").removeEventListener("mousedown", MouseDown, false);
    
    // If we dont have a selected point, then add a new one
    if(mouseOverIndex == -1)
    {
        // Get mouse coords
        var e = event || window.event;
        var pos = getRelativeCoordinates(event, document.getElementById('ImageDiv'));
        
        // Which mode are we in?
        switch(SelectedTool)
        {
            case "Outline":
                SelectedRegion.OutlinePointsX[SelectedRegion.OutlinePointsX.length] = pos.x;
                SelectedRegion.OutlinePointsY[SelectedRegion.OutlinePointsY.length] = pos.y;
                SelectedRegion.isSaved = false;
                RefreshImage();
                break;
            case "CutOut":
                //SelectedRegion.
                break;
            //case "Perspective":
                //var index = SelectedRegion.PerspectivePointsX.length;
                //if(index > 3)
                //{
                //    index = 3;
                //}
                //SelectedRegion.PerspectivePointsX[index] = pos.x;
                //SelectedRegion.PerspectivePointsY[index] = pos.y;
                //SelectedRegion.isSaved = false;
                //break;
        }
        
    }
    return false;
}

var mouseOverIndex = -1;
var mouseDown = false;
var rendering = false;

function MouseMove(event)
{
    var e = event || window.event;
    var pos = getRelativeCoordinates(event, document.getElementById('ImageDiv'));
    
    if(mouseDown)
    {
        if(mouseOverIndex != -1)
        {
            switch(SelectedTool)
            {
                case "Outline":
                    SelectedRegion.OutlinePointsX[mouseOverIndex] = pos.x;
                    SelectedRegion.OutlinePointsY[mouseOverIndex] = pos.y;
                    break;
                case "Perspective":
                    SelectedRegion.PerspectivePointsX[mouseOverIndex] = pos.x;
                    SelectedRegion.PerspectivePointsY[mouseOverIndex] = pos.y;
                    break;
            }
            
            if(!rendering)
            {
                rendering = true;
                RefreshImage();
                rendering = false;
            }
        }
    }
    else
    {
        // Check to see if we are within any of the point elipses
        var newMouseOverIndex = -1;
        //this.style.cursor='crosshair';
        switch(SelectedTool)
        {
            case "Outline":
                for( i = 0; i < SelectedRegion.OutlinePointsX.length; i++)
                {
                    if(Math.abs(pos.x - SelectedRegion.OutlinePointsX[i]) < 3 && Math.abs(pos.y - SelectedRegion.OutlinePointsY[i]) < 3)
                    {
                        newMouseOverIndex = i;
                        //this.style.cursor='move';
                    }
                }
                break;
            case "Perspective":
                for( i = 0; i < SelectedRegion.PerspectivePointsX.length; i++)
                {
                    if(Math.abs(pos.x - SelectedRegion.PerspectivePointsX[i]) < 3 && Math.abs(pos.y - SelectedRegion.PerspectivePointsY[i]) < 3)
                    {
                        newMouseOverIndex = i;
                        //this.style.cursor='move';
                    }
                }
                break;
        }
        if(newMouseOverIndex != mouseOverIndex)
        {
            mouseOverIndex = newMouseOverIndex;
            RefreshImage();
        }
    }
    return false;
}

function MouseUp(event)
{
    mouseDown = false;
    RefreshImage(); // Added (or was it re-added?) 2-9-09 by NeilN
    return false;
}

function RefreshImage()
{
    // Render to the divIndex (the hidden one)
    var jg = jgA[divIndex];
    
    switch(SelectedTool)
    {
        case "Outline":
            jg.setColor(OutlineColor);
            if(SelectedRegion.OutlinePointsX.length > 0)
            {
                jg.setOpacity(1.0);
                if(SelectedRegion.OutlinePointsX.length > 1)
                {
                    jg.drawPolygon(SelectedRegion.OutlinePointsX, SelectedRegion.OutlinePointsY);
                    jg.setOpacity(0.3);
                    jg.fillPolygon(SelectedRegion.OutlinePointsX, SelectedRegion.OutlinePointsY);
                }
                jg.setOpacity(1.0);
                for( i = 0; i < SelectedRegion.OutlinePointsX.length; i++)
                {
                    jg.drawEllipse(SelectedRegion.OutlinePointsX[i]-2, SelectedRegion.OutlinePointsY[i]-2, 4, 4);
                    if(i == mouseOverIndex)
                    {
                        jg.setColor(PerspectiveColor);
                        jg.fillEllipse(SelectedRegion.OutlinePointsX[i]-3,SelectedRegion.OutlinePointsY[i]-3,6,6);
                        jg.setColor(OutlineColor);
                    }
                }
                jg.paint();
            }
            break;
        case "Perspective":
            if(SelectedRegion.PerspectivePointsX.length > 0)
            {
                jg.setOpacity(1.0);
                jg.setColor(PerspectiveColor);
                if(SelectedRegion.PerspectivePointsX.length > 1)
                {                    
                    var pointsX = SelectedRegion.PerspectivePointsX;
                    var pointsY = SelectedRegion.PerspectivePointsY;
                    
                    // Do top and Bottom lines Red
                    //jg.setColor(OutlineColor);
                    jg.drawLine(pointsX[0], pointsY[0], pointsX[1], pointsY[1]);
                    jg.drawLine(pointsX[2], pointsY[2], pointsX[3], pointsY[3])
                    
                    // Do Left and Right Lines Yellow
                    //jg.setColor(PerspectiveColor);
                    jg.drawLine(pointsX[1], pointsY[1], pointsX[2], pointsY[2]);
                    jg.drawLine(pointsX[3], pointsY[3], pointsX[0], pointsY[0])
                    
                    //jg.drawPolygon(SelectedRegion.PerspectivePointsX, SelectedRegion.PerspectivePointsY);
                    
                    if(!mouseDown)
                    {
                        // Declare our temp variables here to help speed up the height and width loops
                        var qX;
                        var qY;
                        var qX2;
                        var qY2;
                        
                        // Loop through the number of units wide this perspective is, minus the last one.
				        for(i = 1; i < SelectedRegion.Width; i++)
				        {
					        // Draw a line for this Interval * the count

					        // Get the point for the top line
					        qX = (SelectedRegion.PerspectivePointsX[1] - SelectedRegion.PerspectivePointsX[0]) * i * (1.0 / SelectedRegion.Width) + SelectedRegion.PerspectivePointsX[0];
					        qY = (SelectedRegion.PerspectivePointsY[1] - SelectedRegion.PerspectivePointsY[0]) * i * (1.0 / SelectedRegion.Width) + SelectedRegion.PerspectivePointsY[0];

					        // Get the Point for the bottom Line
					        qX2 = (SelectedRegion.PerspectivePointsX[2] - SelectedRegion.PerspectivePointsX[3]) * i * (1.0 / SelectedRegion.Width) + SelectedRegion.PerspectivePointsX[3];
					        qY2 = (SelectedRegion.PerspectivePointsY[2] - SelectedRegion.PerspectivePointsY[3]) * i * (1.0 / SelectedRegion.Width) + SelectedRegion.PerspectivePointsY[3];

					        // Draw the Height Line
					        jg.drawLine(qX,qY,qX2,qY2);
				        }
                        //jg.setColor(OutlineColor);
				        // Loop through the number of units high this perspective is, minus the last one.
				        for(i = 1; i < SelectedRegion.Height; i++)
				        {
					        // Draw a line for this Interval * the count

					        // Get the point for the left line
					        qX = (SelectedRegion.PerspectivePointsX[3] - SelectedRegion.PerspectivePointsX[0]) * i * (1.0 / SelectedRegion.Height) + SelectedRegion.PerspectivePointsX[0];
					        qY = (SelectedRegion.PerspectivePointsY[3] - SelectedRegion.PerspectivePointsY[0]) * i * (1.0 / SelectedRegion.Height) + SelectedRegion.PerspectivePointsY[0];

					        // Get the Point for the right Line
					        qX2 = (SelectedRegion.PerspectivePointsX[2] - SelectedRegion.PerspectivePointsX[1]) * i * (1.0 / SelectedRegion.Height) + SelectedRegion.PerspectivePointsX[1];
					        qY2 = (SelectedRegion.PerspectivePointsY[2] - SelectedRegion.PerspectivePointsY[1]) * i * (1.0 / SelectedRegion.Height) + SelectedRegion.PerspectivePointsY[1];

					        // Draw the Height Line
                            jg.drawLine(qX,qY,qX2,qY2);
				        }
                    }
                }
                jg.setOpacity(1.0);
                for( i = 0; i < SelectedRegion.PerspectivePointsX.length; i++)
                {
                    jg.drawEllipse(SelectedRegion.PerspectivePointsX[i]-2,SelectedRegion.PerspectivePointsY[i]-2,4,4);
                    if(i == mouseOverIndex)
                    {
                        jg.setColor(OutlineColor);
                        jg.fillEllipse(SelectedRegion.PerspectivePointsX[i]-3,SelectedRegion.PerspectivePointsY[i]-3,6,6);
                        jg.setColor(PerspectiveColor);
                    }
                }
            }
            jg.paint();
            
            break;
        case "Scale":
            jg.setColor(PerspectiveColor);
            
            if(SelectedRegion.PerspectivePointsX.length > 1)
            {
                //jg.setOpacity(0.1);
                //jg.fillPolygon(SelectedRegion.PerspectivePointsX, SelectedRegion.PerspectivePointsY);
                jg.setOpacity(1.0);
                jg.drawPolygon(SelectedRegion.PerspectivePointsX, SelectedRegion.PerspectivePointsY);

                // Declare our temp variables here to help speed up the height and width loops
                var qX;
                var qY;
                var qX2;
                var qY2;
                
                // Loop through the number of units wide this perspective is, minus the last one.
				for(i = 1; i < SelectedRegion.Width; i++)
				{
					// Draw a line for this Interval * the count

					// Get the point for the top line
					qX = (SelectedRegion.PerspectivePointsX[1] - SelectedRegion.PerspectivePointsX[0]) * i * (1.0 / SelectedRegion.Width) + SelectedRegion.PerspectivePointsX[0];
					qY = (SelectedRegion.PerspectivePointsY[1] - SelectedRegion.PerspectivePointsY[0]) * i * (1.0 / SelectedRegion.Width) + SelectedRegion.PerspectivePointsY[0];

					// Get the Point for the bottom Line
					qX2 = (SelectedRegion.PerspectivePointsX[2] - SelectedRegion.PerspectivePointsX[3]) * i * (1.0 / SelectedRegion.Width) + SelectedRegion.PerspectivePointsX[3];
					qY2 = (SelectedRegion.PerspectivePointsY[2] - SelectedRegion.PerspectivePointsY[3]) * i * (1.0 / SelectedRegion.Width) + SelectedRegion.PerspectivePointsY[3];

					// Draw the Height Line
					jg.drawLine(qX,qY,qX2,qY2);
				}
                
				// Loop through the number of units high this perspective is, minus the last one.
				for(i = 1; i < SelectedRegion.Height; i++)
				{
					// Draw a line for this Interval * the count

					// Get the point for the left line
					qX = (SelectedRegion.PerspectivePointsX[3] - SelectedRegion.PerspectivePointsX[0]) * i * (1.0 / SelectedRegion.Height) + SelectedRegion.PerspectivePointsX[0];
					qY = (SelectedRegion.PerspectivePointsY[3] - SelectedRegion.PerspectivePointsY[0]) * i * (1.0 / SelectedRegion.Height) + SelectedRegion.PerspectivePointsY[0];

					// Get the Point for the right Line
					qX2 = (SelectedRegion.PerspectivePointsX[2] - SelectedRegion.PerspectivePointsX[1]) * i * (1.0 / SelectedRegion.Height) + SelectedRegion.PerspectivePointsX[1];
					qY2 = (SelectedRegion.PerspectivePointsY[2] - SelectedRegion.PerspectivePointsY[1]) * i * (1.0 / SelectedRegion.Height) + SelectedRegion.PerspectivePointsY[1];

					// Draw the Height Line
                    jg.drawLine(qX,qY,qX2,qY2);
				}
            }
            jg.paint();
            break;
    }
    // Swap the zOrders, flip the divIndex
    divA[divIndex].style.zIndex = 3;
    divIndex ^= 1;
    divA[divIndex].style.zIndex = 0;
    jgA[divIndex].clear();
}
