// ----------------------------------------------------------------------------
// COPYRIGHT 1999 DELCAM PLC., BIRMINGHAM, ENGLAND. 
// ----------------------------------------------------------------------------
//
// History.
// Who When     What   
// --- -------- ---------------------------------------------------------
// tpb 24/02/00 Written
// tpb 14/10/03 Added Spin controls
//-----------------------------------------------------------------------------

// Global variables
var gSpinTimeout = null;
var gSpinInterval = null;


//=== SubclassNumberEditControls ==============================================
//
// History
// DICC  Who When     What
// ----- --- -------- ---------------------------------------------------------
// 00000 tpb 21/08/00 Written - Add functionality to edit boxes marked 'number'
//-----------------------------------------------------------------------------

function SubclassNumberEditControls() 
{
  // Loop through all INPUT elements and setup ones marked 'number'
  var tags = document.all.tags("INPUT");
  var idx, tag;
  var count = tags.length;
  for( idx = 0; idx < count; idx ++ )
  {
    tag = tags[idx];
    if( tag.number != null )
    {
      tag.onkeypress    = NumberEdit_OnKeyPress;
      tag.ondblclick    = NumberEdit_OnDblClick;
      tag.setValue      = NumberEdit_SetValue;
      tag.getValue      = NumberEdit_GetValue;
      if( tag.dp != null )
      {
        tag.dp = eval(tag.dp);
        if( tag.dp <= 0 )
        {
          tag.dp = 0;
          tag.integer = true;
        }
      }
      //if( tag.expression != null )
         tag.oncontextmenu = NumberEdit_OnContextMenu;

      // See if a spinner has been requested and add it. The edit control needs to have an ID though.
      if( tag.spin != null )
      {
         if( tag.id.length == 0 )
            artcam.MessageBox("Edit control MUST have an ID specified to use spinner");
         else
         {
            // Get the shared images directory
            var imgdir = artcam.HtmlRootDir + "..\\SharedImages\\";
            var ihtml = "<img align=absmiddle src='"+imgdir+"spinoff.gif' " +
                        " onmousemove='Spin_MouseMove()' " +
                        " onmouseout='Spin_MouseOut()' " +
                        " onmouseup='Spin_ClearTimers()' " +
                        " onmousedown='Spin_MouseDown(\""+tag.id+"\")' " +
                        " ondblclick='Spin_MouseDown(\""+tag.id+"\");Spin_ClearTimers()' " +
                        ">";
            tag.insertAdjacentHTML('afterEnd', ihtml);
         }
      }
    }
  }
}


//=== NumberEdit_OnKeyPress ==============================================
//
// History
// DICC  Who When     What
// ----- --- -------- ---------------------------------------------------------
// 00000 tpb 24/02/00 Written - Overrides Edit boxes to do only numbers
// bem 11/12/02 Default 5 dp for inches
//-----------------------------------------------------------------------------

function NumberEdit_OnKeyPress()
{
  // Ensure spin timers are not running
  Spin_ClearTimers()

  // Allow the following keycodes for navigation
  var ch = event.keyCode;
  if( ch == 0 )
    return;

  // Get the control that started this event.
  var edit = event.srcElement;

  // If keypress is a number check to see if it is before a minus if there.
  var numstr = "09.-";
  if( ch >= numstr.charCodeAt(0) && ch <= numstr.charCodeAt(1) )
  {
    // If there is a minus and we are at the beggining, disallow this keypress
    if( edit.value.charAt(0) == "-" )
    {      
      var editrng = edit.createTextRange();
      var selrng = document.selection.createRange();
      editrng.collapse();
      if( editrng.isEqual( selrng ) )
      {
        event.returnValue = false;
        return;
      }
    }

    // If we have a full stop and our current position is after it, disallow.
    var idx = edit.value.indexOf(".")
    if( idx != -1 )
    {
      // If we are on the right of the decimal point check the number of
      var editrng = edit.createTextRange();
      var selrng = document.selection.createRange();
      if(!editrng.findText(".",0))
      {
        // This is a weird error if this happens!
        event.returnValue = false;
        return;
      }

      // See if we are positioned after the '.'
      if(editrng.compareEndPoints("EndToStart", selrng) <= 0)
      {
        // Get our current decimal place.
        var dp;
        if(edit.dp == null)
           dp = artcam.InMM ? 3 : 5;
        else
          dp = eval( edit.dp );

        // if we have reached our decimal point limit, disallow this!
        if( edit.value.length - idx - 1 - selrng.text.length >= dp )
        {
          event.returnValue = false;
          return;
        }
      }
    }
    return; 
  }



  // If keypress is a fullstop and we can have floats, only allow if there are none in the string.
  if( ch == numstr.charCodeAt(2) && edit.integer == null )
  {
    // We ignore it if we already have one. (We could check to see if it would replace the selection.)
    if( edit.value.indexOf(".") != -1 )
    {
      var selrng = document.selection.createRange();
      if( !selrng.text.length || !selrng.findText(".",0) )
        event.returnValue = false;
    }
    return;
  }



  // If keypress is a '-' AND we allow negative we put in ourselves at start of string and move to beggining after '-'
  if( ch == numstr.charCodeAt(3) && edit.positive == null )
  {      
    var editrng = edit.createTextRange();
    var selrng = document.selection.createRange();
        
    if( edit.value.charAt(0) != "-" )
    {
      // Find out if we have a selection covering the '-' just allow the minus through
      // Otherwise we put it in at the beggining, and move the caret
      if(editrng.compareEndPoints("StartToStart", selrng) != 0 || selrng.text.length == 0 )
      {
	      edit.value = "-" + edit.value;
        editrng.move("character");
        editrng.select();
        event.returnValue = false;
      }
    }
    else
    {
      // If our current seletion is at the beggining, anything selected or not, allow the minus
      // Otherwise we remove it in from the beggining, and move the caret
      if(editrng.compareEndPoints("StartToStart", selrng) != 0 )
      {
        edit.value = edit.value.substr(1);
        editrng.collapse();
        editrng.select();
        event.returnValue = false;  
      }
    }
    return;
  }

  // Otherwise disallow this keypress.
  event.returnValue = false;              
}




//=== NumberEdit_OnDblClick ==============================================
//
// History
// DICC  Who When     What
// ----- --- -------- ---------------------------------------------------------
// 00000 tpb 22/08/00 Written
//-----------------------------------------------------------------------------

function NumberEdit_OnDblClick()
{
  // Get the control that started this event.
  //event.srcElement.select();
}



//=== NumberEdit_SetValue ==============================================
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// tpb 18/05/01 Written
// bem 11/12/02 Default 5 dp for inches
// tpb 19/09/06 Ensure newvalue is forced to be a number
//-----------------------------------------------------------------------

function NumberEdit_SetValue(newvalue)
{
   // Ensure we have a valid number here
   newvalue = parseFloat( newvalue );
   if( isNaN( newvalue ) )
      newvalue = 0;

   // Set the value of this edit box taking into account the dp, positive negative ... etc
   if( newvalue < 0 && this.positive != null )
      newvalue *= -1;
   if( this.integer != null )
   {
      newvalue = Math.round( newvalue );
   }
   else
   {
      // Get our current decimal place.
      var dp;
      if(this.dp == null)
         dp = artcam.InMM ? 3 : 5;
      else
         dp = eval( this.dp );
      if( dp < 0 )
         dp = 0;
      if( dp > 6 )
         dp = 6;
      var shift = Math.pow(10,dp);
      newvalue = Math.round( newvalue * shift ) / shift;
   }

   this.value = newvalue;
}

//=== NumberEdit_GetValue ==============================================
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// bem 23/05/01 Written
//-----------------------------------------------------------------------

function NumberEdit_GetValue()
{
   return parseFloat(this.value);
}


function NumberEdit_OnContextMenu()
{
   // Open up the expression calculator page
   g_CalcWin = window.open( artcam.HtmlRootDir + "jcalc\\jcalc.htm", "jcalc", "width=240,height=300,resizable=yes" );
   g_CalcWin.focus();
   g_CalcWinEdit = this;
   setTimeout( "NumberEdit_SetupCalcWin()", 50 );
   event.returnValue=false; // Stop the menu popping up.
}

g_timeoutcount = 0;
function NumberEdit_SetupCalcWin()
{
   if( g_CalcWin != null && g_CalcWinEdit != null )
   {
      if( g_CalcWin.SetNumberEdit != null )
      {
		g_timeoutcount = 0;
		g_CalcWin.SetNumberEdit( g_CalcWinEdit );
      }
	  else
	  {
	    g_timeoutcount++;
	    if( g_timeoutcount < 50 )
		  setTimeout( "NumberEdit_SetupCalcWin()", 50 );
		else
		  g_timeoutcount = 0;
	  }
   }
}


//=== Spin_MouseMove ==============================================
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// tpb 14/10/03 Written
//-----------------------------------------------------------------------

function Spin_MouseMove()
{
   // If we have a timer running, don't do anything
   if( gSpinTimeout != null || gSpinInterval != null )
      return;

   // Otherwise, change the image accordingly
   var imgdir = artcam.HtmlRootDir + "..\\SharedImages\\";
   if(event.offsetY < 10)
      event.srcElement.src = imgdir + "spinup.gif";
   else
      event.srcElement.src = imgdir + "spindown.gif";
}


//=== Spin_MouseOut ==============================================
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// tpb 14/10/03 Written
//-----------------------------------------------------------------------

function Spin_MouseOut()
{
   Spin_ClearTimers();
   event.srcElement.src = artcam.HtmlRootDir + "..\\SharedImages\\spinoff.gif";
}


//=== Spin_MouseUp ==============================================
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// tpb 14/10/03 Written
//-----------------------------------------------------------------------

function Spin_ClearTimers()
{
   // Clear all the timers
   if( gSpinTimeout != null )
   {
      clearTimeout(gSpinTimeout);
      gSpinTimeout = null;
   }
   if( gSpinInterval != null )
   {
      clearInterval(gSpinInterval);
      gSpinInterval = null;
   }
}


//=== Spin_MouseDown ==============================================
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// tpb 14/10/03 Written
//-----------------------------------------------------------------------

function Spin_MouseDown(tag_id)
{
   // Make sure the spin timers are reset
   Spin_ClearTimers();

   // Do the spin up or down according to mouse position
   var spin_up = event.offsetY < 10;
   Spin_Update(tag_id, spin_up);

   // Start the spin timer, firstly
   gSpinTimeout = setTimeout("Spin_StartInterval('"+tag_id+"', "+spin_up+")", 500);
}


//=== Spin_Update ==============================================
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// tpb 14/10/03 Written
//-----------------------------------------------------------------------
function Spin_Update(tag_id, spin_up)
{
   // Get the tag and the current amount of spin
   var tag = eval(tag_id);
   var amount = eval(tag.spin);

   // And Add/Subtract it accordingly
   if(spin_up)
      tag.setValue(tag.getValue() + amount);
   else
      tag.setValue(tag.getValue() - amount);

   // Update the tag if it has an update function
   if( tag.spinupdate != null )
      eval( tag.spinupdate );
}


//=== Spin_StartInterval ==============================================
//
// History
// Who When     What
// --- -------- ---------------------------------------------------------
// tpb 14/10/03 Written
//-----------------------------------------------------------------------

function Spin_StartInterval(tag_id, spin_up)
{
   gSpinTimeout = null;
   gSpinInterval = setInterval("Spin_Update('"+tag_id+"', "+spin_up+")", 50);
}


