/*
 * ====================== scan.js ========================
 * ======    Javascript include for scan.htm   ===========
 * =======================================================
 *
 *
 * Contributor(s):
 *   Douglas Gennetten (douglas_gennetten@hp.com)
 *   PLH
 *   Mike Yoder (mike_yoder@non.hp.com)
 * 
 * And Jim Tucek of forinti.com for fixing the evasive 
 * explorer script errors.
 *
*/

var paletteWidth = 250;                              // tool palette is currently fixed width
var Units = new Array(1, 2, 3, 4);                   // maps to enum in MagView.idl
var ScanChannel = new Array(0, 1, 2, 3);            // maps to enum in MagView.idl
var Sharpen = new Array(0, 1, 2, 3, 4);            // maps to enum in MagView.idl
var ScanMode = null;                                  // default ScanMode is Image
var RecFlag = false;
var pal = new Array;                              // global tool palette management object
var vHLDropper = false;
var vSDropper = false;
var OrgNumStr = "";                                 //Store the "#x of #y" string, so we wouldn't keep getting it from string file
var ToolPalettesDone = 0;
var KeepTrckImageType = null;
var ScanErrors = new Array(12, 6, 7, 4, 10, 2, 25, 3, 5, 8, 11, 24, 14, 15, 16, 17, 18, 26, 28, 27, 29, 30, 31, 32); //mapping to the errors within hpiscn.idl
var preshowdone = false;
var mitem="show-menu=output";
var sitem="show-menu=scan";
var bitem="show-menu=basic";
var aitem="show-menu=advanced";
var hitem="show-menu=help";
var DotIsDecimal;

///////////////////////////////////////////////////////////////////////
////     window & document event assignments. Do Not Hijack!       ////
///////////////////////////////////////////////////////////////////////

document.onload= fnOnLoad; 
document.onmousedown = fnOnMouseDown;
document.onmouseup = fnOnMouseUp;
document.onmousemove = fnOnMouseMove;
window.onresize = fnOnResize;

// HACK HACK HACK
// For some reason, certain calls to VBfmtnum() fail
// Here it is implemented in Javascript instead
function fixed_fmtnum(value,places) {
	var temp = Math.pow(10,places);
	var rounded = Math.round(value*temp);
	return (rounded / temp);
}


//Do not call any scancontrol in this function. 
//If needed, please do it in exPreShowUI.
function fnOnLoad() {
   if (is_ie4) positionElements();   
   setupToolPalettes();   
   setupToolTips();                     
   pushSelectOptions(oScanChannel, channelgray, channelred, channelgreen,channelblue);
   pushSelectOptions(oSharpen, sharpennone, sharpenlow, sharpenmedium ,sharpenhigh, sharpenextreme);
   pushSelectOptions(oUnitsSel, unitinches, unitcm, unitpoints, unitpixels);   
   setupScanMode();
   if (!is_ie4) UIfinalize();
}

function fnOnResize() {
   if (is_ie4) positionElements();                
}

function fnOnMouseDown(){
   slider_onmousedown();
   button_onmousedown();
}
function fnOnMouseUp(){
   slider_onmouseup();
   button_onmouseup();
}
function fnOnMouseMove(){
   slider_onmousemove();   
}

///////////////////////////////////////////////////////////////////////
////   UI Initialization functions (called by above handlers)      ////
///////////////////////////////////////////////////////////////////////

function UIfinalize() {
	// Resolution Combo Box
	ResComboBoxID.style.position="absolute";
	ResComboBoxID.tabIndex=-1;
	ResComboBoxID.style.setExpression("posTop", "txtresolution.offsetTop-1", "JScript");
	ResComboBoxID.style.setExpression("posLeft", "txtresolution.offsetLeft", "JScript");
	ResComboBoxID.style.setExpression("posHeight", "txtresolution.clientHeight", "JScript");
	ResComboBoxID.style.setExpression("clip","'rect(auto auto auto '+(txtresolution.clientWidth-2)+')'", "JScript");
	txtresolution.size = 6;
	txtresolution.style.marginRight='16px';
	txtresolution.style.posWidth=ResComboBoxID.clientWidth-16;
	// Scale Combo Box
	oScale.style.position="absolute";
	oScale.tabIndex=-1;
	oScale.style.setExpression("posTop", "txtscale.offsetTop", "JScript");
	oScale.style.setExpression("posLeft", "txtscale.offsetLeft", "JScript");
	oScale.style.setExpression("posHeight", "txtscale.clientHeight", "JScript");
	oScale.style.setExpression("clip","'rect(auto auto auto '+(txtscale.clientWidth-3)+')'", "JScript");
	txtscale.size = 5
	txtscale.style.posWidth = oScale.clientWidth-16;
}

function setupToolPalettes() {
   pal['resize'] = new toolPalette('resize');
   pal['exposure'] = new toolPalette('exposure');
   pal['sharpen'] = new toolPalette('sharpen');
   pal['coloradj'] = new toolPalette('coloradj');
   pal['resolution'] = new toolPalette('resolution');
   pal['threshold'] = new toolPalette('threshold');
   ToolPalettesDone = 1;
}

function setupScanMode(){
   tImageType.dataFld= "output-type-0";
}

function setupToolTips() {
   var stringsRS = tdcStrings.recordset;
   OrgNumStr = stringsRS('tip-number-pages');
   imgPopout.alt = stringsRS('tip-pop-out');
   imgPopin.alt = stringsRS('tip-pop-in');
   imgNextPage.alt = stringsRS('tip-next-page');
   imgPrevPage.alt = stringsRS('tip-previous-page');
   imgTool1.alt = stringsRS('tip-rotate-left');   
   imgTool2.alt = stringsRS('tip-rotate-right');   
   imgTool3.alt = stringsRS('tip-zoom-in');   
   imgTool4.alt = stringsRS('tip-zoom-out');   
   imgNewScanButton.alt = stringsRS('tip-new-scan-button');
   lblResize.title = stringsRS('tip-resize');
   lblExposure.title = stringsRS('tip-exposure');
   lblColor.title = stringsRS('tip-color');
   lblSharpen.title = stringsRS('tip-sharpen');
   lblThreshold.title = stringsRS('tip-threshold');
   lblResolution.title = stringsRS('tip-resolution');
   areaHide.title = stringsRS('tip-hide-tools');
   areaCollapse.title = stringsRS('tip-collapse-all');
   areaExpand.title = stringsRS('tip-expand-all');
   lblMirror.title = stringsRS('tip-mirror-off');
   mirrorOff.title = stringsRS('tip-mirror-off');
   lblInvert.title = stringsRS('tip-invert-off');
   invertOff.title = stringsRS('tip-invert-off');
   lblDescreen.title = stringsRS('tip-descreen-off');
   descreenOff.title = stringsRS('tip-descreen-off');
   lblReset.title = stringsRS('tip-reset-tools');
   imgReset.title = stringsRS('tip-reset-tools');
}

///////////////////////////////////////////////////////////////////////
////       MagView Event Handler's (see bottom of scan.htm)        ////
///////////////////////////////////////////////////////////////////////

function scanUpdateControls() {                     // responds to OnUIChange from scan control

   //If ScanMode hasn't been set, don't continue
   if (ScanMode == null) return;
   GlassOrTMA(); //Checking to see if I am scanning from glass or tma.
   UpdatePageNumberinMPP(); //Updating the page numbers for Multipage preview.

   UpdateResSizeScale(); //update the info panel
   if (ScanMode ==1 ) { //document mode
      oInfoText1.style.display = "none"; //Turned on the display of output type.
       resol.style.color = "#778899";
       resol.style.cursor ="default";
      
   } 
   else { //image mode
	   if(KeepTrckImageType == null) {
		  KeepTrckImageType = scanControl.ImageType;
		  tOutputType.dataFld =  "output-" + scanControl.ImageType;      // switch TDC dataFld to match imageType
		   resol.style.color = "#000000";
		   resol.style.cursor = "hand";
	   }
	   else if(KeepTrckImageType != scanControl.ImageType){
		  KeepTrckImageType = scanControl.ImageType;
		  tOutputType.dataFld =  "output-" + scanControl.ImageType;      // switch TDC dataFld to match imageType
	   }
	}
	PreviewImgValid();

   //if invert is true then reflect it in the icon.
   if(scanControl.InvertColors == false) {
		invertOn.style.display = "none";
		invertOff.style.display = "";
	} 
	
	if( scanControl.Mirror == false) {
		mirrorOff.style.display = "";
		mirrorOn.style.display = "none";
	}

	if(scanControl.DemoireEnabled == false) {
      descreenOff.style.display = "";
      descreenOn.style.display = "none";
	}


   //Address the issue that onload is not done loading and an
   //event occurs.
   if(ToolPalettesDone == 1) {

      if(pal['resolution'].isOpen())
         UpdateRes();
      if(pal['sharpen'].isOpen())
         UpdateSharpen();
      if(pal['resize'].isOpen())
         UpdateResize();
      if(!RecFlag){
         RecFlag = true;

         if(pal['exposure'].isOpen()) {
         if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
            UpdateTMAExposureSliders();
         else {
               UpdateExposureSliders();
              UpdateExpLevel();                            //Update the Black & White Level Exposure
         }
         }
         if(pal['threshold'].isOpen())
            UpdateThresholdSliders();

         if(pal['coloradj'].isOpen())
            UpdateColorSliders();
         RecFlag = false;
      }

      //Based on the imageType we will gray out the
      //certain tools within the tool panel.  But we should
      //only do that if we are in image mode
      switch(scanControl.ImageType) {
         case 0: // true color
         case 1: //Opt Palette
         case 2: //Web Palette
         case 3: //System Palette
         case 4: //Spot
            pal['threshold'].grayOut(); //bw threshold
            bwt.style.color = "#778899";//(#778899
            bwt.style.cursor = "default";
            pal['coloradj'].unGrayOut();  //color 
            coladj.style.color = "#000000";
            coladj.style.cursor = "hand";
            pal['exposure'].unGrayOut(); //exposure
            exposure.style.color = "#000000";
            exposure.style.cursor = "hand";
            break;
         case 5: //Grayscale
            pal['exposure'].unGrayOut();
            exposure.style.color = "#000000";
            exposure.style.cursor = "hand";
            pal['threshold'].grayOut(); 
            bwt.style.color = "#778899";
            bwt.style.cursor ="default";
            pal['coloradj'].grayOut();
            coladj.style.color = "#778899";
            coladj.style.cursor = "default";
            break;
         case 6: // B & W
            pal['exposure'].grayOut(); 
            exposure.style.color = "#778899";
            exposure.style.cursor = "default";
            pal['coloradj'].grayOut();
            coladj.style.color = "#778899";
            coladj.style.cursor = "default";
            pal['threshold'].unGrayOut(); 
            bwt.style.color = "#000000";
            bwt.style.cursor = "hand";
            break;
         default:
            break;
      }
   }
   //////////////////////
 //Not supported in IE4.0
   if (!is_ie4) {
	   oNewscanButton.blur();
	   oScanButton.blur();
	   imgTool1.blur();
	   imgTool2.blur();
	   imgTool3.blur();
	   imgTool4.blur();
	}
}

function scanDimensionChange() {
   oInfoText1.style.visibility = "visible";
   oInfoText2.style.visibility = "visible";
   //oInfoText3.style.visibility = "visible";

   Isize = scanControl.ImageSize;  //returns megabyte

   if (Isize < 1.0) { FIsize = Isize * 1000.0; valuebyte = kb.innerText; }
   else if (Isize < 1000) { FIsize = Isize; valuebyte = mb.innerText; }
   else if (Isize < 1000000) { FIsize = Isize/1000.0; valuebyte = gb.innerText;}
   else { FIsize = Isize/1000000.0; valuebyte = tb.innerText;}
   
   tImageSize.innerText = fixed_fmtnum(FIsize, 2) + valuebyte;
   tResolution.innerText = fixed_fmtnum(scanControl.FinalResolution,0);
      
   if(oUnitsSel.options.length > 0)
      units.innerText = oUnitsSel[scanControl.OutputUnits-1].text;

    Scale = fixed_fmtnum(scanControl.PercentScale, 0);
    tScale.innerText = txtscale.value=Scale + '%';

    //If units are in inches or cm, we will display 2 decimal place otherwise just 1.
   if   ((Units[oUnitsSel.value] == 1) || ( Units[oUnitsSel.value] ==2)){
      ht.innerText = oht.value = fixed_fmtnum(scanControl.OutputHeight, 2);
      wd.innerText = owd.value = fixed_fmtnum(scanControl.OutputWidth, 2);
      sht.value = fixed_fmtnum(scanControl.SelectionHeight, 2);
      swd.value = fixed_fmtnum(scanControl.SelectionWidth, 2);
   }
   else if(Units[oUnitsSel.value] == 3){
      ht.innerText = oht.value = fixed_fmtnum(scanControl.OutputHeight, 1);
      wd.innerText = owd.value = fixed_fmtnum(scanControl.OutputWidth, 1);
      sht.value = fixed_fmtnum(scanControl.SelectionHeight, 1);
      swd.value = fixed_fmtnum(scanControl.SelectionWidth, 1);
   }
   else {
      ht.innerText = oht.value = fixed_fmtnum(scanControl.OutputHeight, 0);
      wd.innerText = owd.value = fixed_fmtnum(scanControl.OutputWidth, 0);
      sht.value = fixed_fmtnum(scanControl.SelectionHeight, 0);
      swd.value = fixed_fmtnum(scanControl.SelectionWidth, 0);
   }
}

function scanLampWarmupMssg() {
   if(!scanControl.LampWarm)
      oLampwarmup.style.display="block";
   else
      oLampwarmup.style.display="none";
}

function scanDrawImage() {
   scanControl.style.width = scanControl.DrawRectWidth;
   scanControl.style.height = scanControl.DrawRectHeight;
}

function scanErrors(){                              // reponds to onError
   var ErrorStrRS = tdcStrings.recordset;
   var i = 0;
   var mssg;

   if (scanControl.LastError == 1)
      return;
	
   while ((i<24) && (ScanErrors[i] != scanControl.LastError)) {
      i++;
   }
   if (scanControl.LastError == 9) 
      mssg = ErrorStrRS('scan-error-9');
   else if (scanControl.LastError == 21)
      mssg = ErrorStrRS('scan-error-10');
   else {
      if(i == 24) i++;

      temp = "scan-error-" + i;
      mssg = ErrorStrRS(temp);
   }
   alert(mssg);

   //If an error occur, and for some reason the 
   //Lamp Warmup message is up turn it off.  We
   //don't want it to stay up.
   oLampwarmup.style.display="none";

}

function UpdateResSizeScale(){
   Isize = scanControl.ImageSize;  //returns megabyte


   if (Isize < 1.0) { FIsize = Isize * 1000.0; valuebyte = kb.innerText; }
   else if (Isize < 1000) { FIsize = Isize; valuebyte = mb.innerText; }
   else if (Isize < 1000000) { FIsize = Isize/1000.0; valuebyte = gb.innerText;}
   else { FIsize = Isize/1000000.0; valuebyte = tb.innerText;}
   tImageSize.innerText = fixed_fmtnum(FIsize, 2) + valuebyte;

   tResolution.innerText = fixed_fmtnum(scanControl.FinalResolution,0);
    Scale = fixed_fmtnum(scanControl.PercentScale, 0);
    tScale.innerText = txtscale.value=Scale + '%';
}

function PreviewImgValid(){
   if(!scanControl.PreviewValid) {
      button_grayout('imgTool1');
      button_grayout('imgTool2');
      button_grayout('imgTool3');
	   button_grayout('imgTool4');
      rr.style.display = "none";  
      rl.style.display = "none";    
      zi.style.display = "none";
      zo.style.display = "none";            
   }
   else { //Preview is valid
      button_ungrayout('imgTool1');
      button_ungrayout('imgTool2');        
      rr.style.display = "block";   
      rr.style.color = "#000000";
      rr.style.cursor = "hand";
      rl.style.display = "block";
      rl.style.color = "#000000"; 
	   rl.style.cursor = "hand"; 
      if (scanControl.SelectionMade) {
         button_ungrayout('imgTool3');         
         zi.style.display = "block";
         zi.style.color = "#000000"; 
         zi.style.cursor = "hand";         
      }
	  else {
         button_grayout('imgTool3');         
         zi.style.display ="none";
         zi.style.color = "#778899"; 
         zi.style.cursor = "default";         
	  }

	   if(scanControl.CanUnZoom) {
		  button_ungrayout('imgTool4');		  
		  zo.style.display = "block";
		  zo.style.color = "#000000";
		  zo.style.cursor = "hand";		   
	   }
	   else {
		  button_grayout('imgTool4');
		  zo.style.display = "none";
		  zo.style.color = "#778899";
		  zo.style.cursor = "default";		   
	   }
   }
   if (scanControl.SelectionMade || scanControl.CanUnZoom)
   {
   	zoom.style.color = "#000000";
   }
   else 
   {
   	zoom.style.color = "#778899";
   }
}

function UpdateSharpen(){
   var sVal = scanControl.SharpenLevel;
   if(oSharpen.options.length > 0)
        oSharpen.options[sVal].selected = true;
}

function UpdateRes(){
  var sVal = VBfmtnum(scanControl.FinalResolution,0);
   var i = 0;

   //Check to see if the value is in the drop down list.
   //If it is than set that to be selected.
   while(i<ResComboBoxID.options.length){
		if(sVal == ResComboBoxID.options[i].value){
			ResComboBoxID.options[i].selected = true;
			break;
		}
		i++;
	}

	//Otherwise set the selected to be the empty one
	if(i==ResComboBoxID.options.length) {
		ResComboBoxID.options[0].selected = true;

	}

   txtresolution.value = sVal;
}

function scanHistogramChange() {
   //if the palette is open then update it.

   if(pal['threshold'].isOpen())
      LoadBWHistogram();

   if(pal['exposure'].isOpen())
      LoadExHistogram();

}

function LoadExHistogram(){                           // Exposure Histogram

   scanControl.SetHistogramDimensions(128,50);
   var hist = (new VBArray(scanControl.Histogram)).toArray();

   if (hist.length != 128)
      return;

   myHisto = new histogram(ExHistogram,50,128,128,hist)
}

function LoadBWHistogram(){                     // B&W Histogram

   var hist = (new VBArray(scanControl.HistogramBW)).toArray();

   if (hist.length != 128)
      return;
   
   myHisto = new histogram(BWHistogram,50,128,128,hist)
   
}
function UpdatePageNumberinMPP() {
   if (scanControl.NumberOfPages <= 1){
		if (oPagingControl.className == "show") {
	         oPagingControl.className = "hide";
		     oPagingText.className = "hide";
		 }
	}

   if (scanControl.NumberOfPages > 1){

	 ///////Disable descreen in multipage preview.
     descreenobj.className="title-grayed";
     button_grayout('descreenOff');
     button_grayout('descreenOn');
     des.style.color = "#778899";
	 ///////////

      if(oPagingControl.className != "show") {
         oPagingControl.className = "show";
		 if(outtitle.style.display != "block") { 
      		outtitle.style.color = "#778899"; 
      		img0id.style.display = "none";
      		img1id.style.display = "none";
      		img2id.style.display = "none";
      		img3id.style.display = "none";
      		img5id.style.display = "none";
      		img6id.style.display = "none";  
		}
      }
      var joy = null;
      var joy1 = null;

      //Hiding the text and changing the values and then 
      //showing the text again.
      oPagingText.className = "hide";
      oPageNum.innerText = OrgNumStr;
      var nstr1 = new String(oPageNum.innerText);
      joy = nstr1.replace("#X", scanControl.CurrentPage);
      joy1 = joy.replace("#Y", scanControl.NumberOfPages);
      oPageNum.innerText = joy1;
      oPagingText.className = "show";

      // If current page is equal to total page, next is disable, previous is enable
      if(scanControl.CurrentPage == scanControl.NumberOfPages){
		  imgNextPage.disabled = true;
		  button_grayout('imgNextPage');
		  imgPrevPage.disabled = false;   
		  button_ungrayout('imgPrevPage');
      }
      else { //otherwise next is enabled
         imgNextPage.disabled = false;
         button_ungrayout('imgNextPage');
      }

	   // if current page is equal to 1 then previous is disabled, next is enabled.
	   if(!(scanControl.CurrentPage > 1)){
		  imgNextPage.disabled = false;
		  button_ungrayout('imgNextPage');
		  imgPrevPage.disabled = true;
		  button_grayout('imgPrevPage');
	   }
	   else { // otherwise previous is enable.
		  imgPrevPage.disabled = false;   
		  button_ungrayout('imgPrevPage');
	   }
   }
}

///////////////////////////////////////////////////////////////////////
////                 UI Event Handler for Scan.htm                 ////
///////////////////////////////////////////////////////////////////////

function fnLaunchPreview(){
	scanControl.style.width = oScanCanvas.style.pixelWidth - 10;
	scanControl.style.height = oScanCanvas.style.pixelHeight - 10;
	if (is_ie4) {
		setTimeout('scanControl.preview();', 0);
   	} else {
		scanControl.getClientRects();
		setTimeout('scanControl.preview();', 0);
	   
	}

}

function fnZoom() {
   scanControl.style.width = oScanCanvas.style.pixelWidth - 10;
   scanControl.style.height = oScanCanvas.style.pixelHeight - 10;

	if (is_ie4) {
		setTimeout('scanControl.Zoom();', 0);
	} else {
	   scanControl.getClientRects();
	   scanControl.Zoom();
	}
}

function fnRotateLeft(){

   scanControl.RotateCounterClockwise();
   button_ungrayout('imgTool1');
   button_ungrayout('imgTool2');
   rr.style.display = "block";
   rr.style.color = "#000000";
   rr.style.cursor = "hand";
   rl.style.display = "block";
   rl.style.color = "#000000";   
   rl.style.cursor = "hand";
   if(scanControl.SelectionMade) {
      button_ungrayout('imgTool3');
      zi.style.display = "block";
      zi.style.color = "#000000";
      zi.style.cursor = "hand";
   }

   if(scanControl.CanUnZoom){
      button_ungrayout('imgTool4');
      zo.style.display = "block";
      zo.style.color = "#000000";
      zo.style.cursor = "hand";
   }

}

function fnRotateRight(){
   scanControl.RotateClockwise();
   button_ungrayout('imgTool1');
   button_ungrayout('imgTool2');
   rr.style.display = "block";
   rr.style.color = "#000000";
   rr.style.cursor = "hand";
   rl.style.display = "block";
   rl.style.color = "#000000";   
   rl.style.cursor = "hand";
   if(scanControl.SelectionMade)
   {
      button_ungrayout('imgTool3');
      zi.style.display = "block";
      zi.style.color = "#000000";
      zi.style.cursor ="hand";
   }

   if(scanControl.CanUnZoom)
   {
      button_ungrayout('imgTool4');
      zo.style.display = "block";
      zo.style.color = "#000000";
      zo.style.cursor = "hand";
   }
}

function fnSelRes(val) {
	if(!val) return; //If the selected is the first and do nothing.
	scanControl.FinalResolution=val;
	txtresolution.value=val;
}

function fnEditRes(val) {
   var i = 0;
   //Check to see if the value is in the drop down list.
   //If it is than set that to be selected.
   while(i<ResComboBoxID.options.length){
		if(val == ResComboBoxID.options[i].value){
			ResComboBoxID.options[i].selected = true;
			break;
		}
		i++;
	}
	//Otherwise set the selected to be the empty one
	if(i==ResComboBoxID.options.length) {
		ResComboBoxID.options[0].selected = true;
	}

	if(isNaN(val)){
		txtresolution.select();
		return;
	}

	scanControl.FinalResolution=val;
}

function fnSelScale(val) {
	if(!val) return; //If the selected is the first and do nothing.
	scanControl.PercentScale = val;
	txtscale.value = val + '%';
}

function fnEditScale(val) {

   var i = 0;
   //Check to see if the value is in the drop down list.
   //If it is than set that to be selected.
   while(i<oScale.options.length){
		if(val == oScale.options[i].value){
			oScale.options[i].selected = true;
			break;
		}
		i++;
	}

	//Otherwise set the selected to be the empty one.
	if(i == oScale.options.length) {
		oScale.options[0].selected = true;
	}

   scanControl.PercentScale=val;
}
 
// Handle Slider Inc/Dec Events
function fnIncrement(sliderID) {         
   var temp = null;                                    
   var val = null;
   temp = eval("document.all."+sliderID);
   val = temp.inc/(temp.max - temp.min);
   setValue(eval(sliderID), fmtnum(temp.value + val, 20));
}

function fnDecrement(sliderID) {                                             
   var temp = null;
   var val = null;
   temp = eval("document.all."+sliderID);
   val = temp.inc/(temp.max - temp.min);
   setValue(eval(sliderID), fmtnum(temp.value - val, 20));
}

// handle Hue Wheel events
function fnOnChangeHue(x, y) {
   scanControl.MidtoneHueX = (x-.5)*2
   scanControl.MidtoneHueY = (y-.5)*2
}
function fnHueBump(dir)   {
   tempX =   huePointer.valueX
   tempY =   huePointer.valueY
   switch ( dir ) {
   case 'g' :
      setValue2(huePointer, tempX, tempY - .005)
      break;
   case 'm' :
      setValue2(huePointer, tempX, tempY + .005)
      break;
   case 'y' :
      setValue2(huePointer, tempX + .005, tempY - .005 * (.75) )
      break;
   case 'r' :
      setValue2(huePointer, tempX + .005, tempY + .005 * (.75) )
      break;
   case 'b' :
      setValue2(huePointer, tempX - .005, tempY + .005 * (.75) )
      break;
   case 'c' :
      setValue2(huePointer, tempX - .005, tempY - .005 * (.75) )
      break;
   }
}

// Called in scanUpdateControls() and fnOpenClose()
function UpdateExposureSliders() {
   setValue1(highlights, scanControl.Highlight/65535);
   setValue1(midtone, (scanControl.MidtoneGamma-1)/3);
   setValue1(shadow, scanControl.Shadow/65535);
    highlightEntry.innerText = VBfmtnum(scanControl.Highlight/257, 0);
   midtoneEntry.innerText = VBfmtnum(scanControl.MidtoneGamma, 2);
   shadowEntry.innerText = VBfmtnum(scanControl.Shadow/257, 0);
}
// Called in scanUpdateControls() and fnOpenClose()
function UpdateTMAExposureSliders() {
   setValue1(highlights, (scanControl.Highlight/200 + .5));
   setValue1(midtone, (scanControl.MidtoneGamma/200 + .5));
   setValue1(shadow, (scanControl.Shadow/200 +.5));
   highlightEntry.innerText = VBfmtnum(scanControl.Highlight, 0);
   midtoneEntry.innerText = VBfmtnum(scanControl.MidtoneGamma, 0);
   shadowEntry.innerText = VBfmtnum(scanControl.Shadow, 0);
}

function UpdateThresholdSliders(){
   setValue1(threshold, scanControl.BlackWhiteThreshold/65535);
    bwthresholdEntry.innerText = VBfmtnum(scanControl.BlackWhiteThreshold/257, 0);
   
   //Updating the scan channel.
   var sVal = scanControl.BlackWhiteScanChannel;
   if(oScanChannel.options.length > 0)
      oScanChannel.options[sVal].selected = true;
}
function UpdateColorSliders(){
   //Update the text first b/c updating the text cause the sliders to move on IE 5.5
   saturationEntry.innerText = VBfmtnum(scanControl.Saturation*100, 0);
   hueXEntry.innerText = VBfmtnum(scanControl.MidToneHueX*100,0);
   hueYEntry.innerText = VBfmtnum(-scanControl.MidToneHueY*100,0);

   if(scanControl.EnhancedColorEnabled)
	radioAdvancedColor.checked = true;
   else
        radioNormalColor.checked = true;

   setValue1(saturation, scanControl.Saturation/1.5);
   setValue2b(huePointer, scanControl.MidtoneHueX/2 +.5, scanControl.MidtoneHueY/2 + .5); 
}

function UpdateExpLevel() {
   setValue1(blacklevel, scanControl.BlackLevel/65535);
   setValue1(whitelevel, scanControl.WhiteLevel/65535);
   whitelevelEntry.innerText = VBfmtnum(scanControl.WhiteLevel/257, 0);
   blacklevelEntry.innerText = VBfmtnum(scanControl.BlackLevel/257, 0);
}



///////////////////////////////////////////////////////////////////////
////   Tool Palette Button Handlers (non-opening palette)          ////
///////////////////////////////////////////////////////////////////////

// Mirror
function fnMirror() {
   scanControl.Mirror = !scanControl.Mirror
   mirrorOff.style.display=(mirrorOff.style.display!="none" ? mirrorOff.style.display="none" : mirrorOff.style.display="")
   mirrorOn.style.display=(mirrorOn.style.display!="none" ? mirrorOn.style.display="none" : mirrorOn.style.display="")
}

// Invert
function fnInvert() {
   scanControl.InvertColors = !scanControl.InvertColors
   invertOff.style.display=(invertOff.style.display!="none" ? invertOff.style.display="none" : invertOff.style.display="")
   invertOn.style.display=(invertOn.style.display!="none" ? invertOn.style.display="none" : invertOn.style.display="")
}

// Descreen
function fnDescreen() {
    originalSrc = descreenOff.src;
   if ( originalSrc.indexOf('_f4')=='-1' ) {   // if not grayed
      scanControl.DemoireEnabled = !scanControl.DemoireEnabled;
      descreenOff.style.display=(descreenOff.style.display!="none" ? descreenOff.style.display="none" : descreenOff.style.display="");
      descreenOn.style.display=(descreenOn.style.display!="none" ? descreenOn.style.display="none" : descreenOn.style.display="");
   }
}

// Reset Tools
function fnResetTools() {
   scanControl.ResetControls();

   //Resetting the eyedroppers
   highlightDropperOn.style.display = "none";
   shadowDropperOn.style.display = "none";
   highlightDropperOff.style.display = "";
   shadowDropperOff.style.display = "";

   //Gamut alarms doesn't get reset.
   
   //Resetting Invert
   invertOn.style.display = "none";
   invertOff.style.display = "";

   //resetting mirror
   mirrorOn.style.display = "none";
   mirrorOff.style.display = "";

   //Descreen
	descreenOn.style.display = "none";
	descreenOff.style.display = "";
}

///////////////////////////////////////////////////////////////////////
////                   Tool Palette Handlers                       ////
///////////////////////////////////////////////////////////////////////

///////////////
/// Gamut Alarms * Eyedroppers
function fnShadowAlarm() {
   shadowAlarmOff.style.display=(shadowAlarmOff.style.display!="none" ? shadowAlarmOff.style.display="none" : shadowAlarmOff.style.display="")
   shadowAlarmOn.style.display=(shadowAlarmOn.style.display!="none" ? shadowAlarmOn.style.display="none" : shadowAlarmOn.style.display="")
}
function fnHighlightAlarm() {
   highlightAlarmOff.style.display=(highlightAlarmOff.style.display!="none" ? highlightAlarmOff.style.display="none" : highlightAlarmOff.style.display="")
   highlightAlarmOn.style.display=(highlightAlarmOn.style.display!="none" ? highlightAlarmOn.style.display="none" : highlightAlarmOn.style.display="")
}
function fnHighlightEyedropper() {
   highlightDropperOff.style.display=(highlightDropperOff.style.display!="none" ? highlightDropperOff.style.display="none" : highlightDropperOff.style.display="")

   if(highlightDropperOn.style.display !="none"){
      highlightDropperOn.style.display ="none";
      scanControlDiv.releaseCapture();
      vHLDropper=false;
   } else {
      highlightDropperOn.style.display ="";
      scanControlDiv.setCapture();
      vHLDropper=true;
   }

}
function fnShadowEyedropper() {
   shadowDropperOff.style.display=(shadowDropperOff.style.display!="none" ? shadowDropperOff.style.display="none" : shadowDropperOff.style.display="")

   if(shadowDropperOn.style.display!="none"){
      shadowDropperOn.style.display ="none";
      scanControlDiv.releaseCapture();
      vSDropper=false;
   } else {
      shadowDropperOn.style.display ="";
      scanControlDiv.setCapture();
      vSDropper=true;
   }

}

function GiveHex(Dec)
{
   if(Dec == 10)
      Value = "A";
   else
   if(Dec == 11)
      Value = "B";
   else
   if(Dec == 12)
      Value = "C";
   else
   if(Dec == 13)
      Value = "D";
   else
   if(Dec == 14)
      Value = "E";
   else
   if(Dec == 15)
      Value = "F";
   else
      Value = "" + Dec;

   return Value;
}

function twoHexDigits(n) {
	return ("00" + n.toString(16)).slice(-2);
}

function rgbToColor(r, g, b) {
	return "#" + twoHexDigits(r) + twoHexDigits(g) + twoHexDigits(b);
}

function fnCapMouseMove(x, y) {
	var s = "-1"
	color = scanControl.GetPixelValue(x, y);
//	if (color != -1)
//	{
		//alert(color);
//	   if(vHLDropper){ //Highlight dropper
//		   Red = RVal.innerText = color & 0x0ff;
//		   Green = GVal.innerText = (color & 0x0ff00) >> 8;
//		   Blue = BVal.innerText = (color & 0x0ff0000) >> 16;

//		   a = twoHexDigits(Red) ;
//		   b = GiveHex(Red % 16);
//		   c = GiveHex(Math.floor(Green / 16));
//		   d = GiveHex(Green % 16);
//		   e = GiveHex(Math.floor(Blue / 16));
//		   f = GiveHex(Blue % 16);

//			displayRGB.style.backgroundColor= rgbToColor(Red, Green, Blue);
//	   }

//	   if(vSDropper){ //shadow dropper
//			Red =  color & 0x0ff;
//			Green =  (color & 0x0ff00) >> 8;
//			Blue = (color & 0x0ff0000) >> 16;
//
//			RVal.innerText = Red;
//			GVal.innerText = Green;
//			BVal.innerText = Blue;

//			a = GiveHex(Math.floor(Red / 16));
//			b = GiveHex(Red % 16);
//			c = GiveHex(Math.floor(Green / 16));
//			d = GiveHex(Green % 16);
//			e = GiveHex(Math.floor(Blue / 16));
//			f = GiveHex(Blue % 16);

//			displayRGB.style.backgroundColor= rgbToColor(Red,Green, Blue);
//		}
//	}
}

function fnCapMouseDown(x, y) {
//	RVal.innerText = "";
//	GVal.innerText = "";
//	BVal.innerText = "";
//	displayRGB.style.backgroundColor= "#000000";
	if(vHLDropper){ //Highlight dropper
		scanControl.SetHighlightFromPoint(window.event.clientX, window.event.clientY); //MagViewCtl.SetHighlightFromPoint(event.x, event.y);
		fnHighlightEyedropper();
		highlightDropperOff.src = "img/eye-dropper.bmp";
	}
	if(vSDropper){ //shadow dropper
	  scanControl.SetShadowFromPoint(window.event.clientX, window.event.clientY); //MagViewCtl.SetHighlightFromPoint(event.x, event.y);
	  fnShadowEyedropper();
	  shadowDropperOff.src = "img/eye-dropper.bmp";
	}
}

/////////
// Resize

/////////////////////////
// Update the Resize tool
function UpdateResize(){

   //If units are in inches or cm, we will display 2 decimal place otherwise just 1.
   if ((Units[oUnitsSel.value] == 1) || ( Units[oUnitsSel.value] ==2)){
      sht.value = VBfmtnum(scanControl.SelectionHeight, 2);
      swd.value = VBfmtnum(scanControl.SelectionWidth, 2);
      oht.value = VBfmtnum(scanControl.OutputHeight, 2);
      owd.value = VBfmtnum(scanControl.OutputWidth, 2);
   }
   else if (Units[oUnitsSel.value] == 3){
      sht.value = VBfmtnum(scanControl.SelectionHeight, 1);
      swd.value = VBfmtnum(scanControl.SelectionWidth, 1);
      oht.value = VBfmtnum(scanControl.OutputHeight, 1);
      owd.value = VBfmtnum(scanControl.OutputWidth, 1);
   }
   else
   {
      sht.value = VBfmtnum(scanControl.SelectionHeight, 0);
      swd.value = VBfmtnum(scanControl.SelectionWidth, 0);
      oht.value = VBfmtnum(scanControl.OutputHeight, 0);
      owd.value = VBfmtnum(scanControl.OutputWidth, 0);

   }

    //UPDATING SCALE
  Scale = VBfmtnum(scanControl.PercentScale, 0);
   var i = 0;
   //Check to see if the value is in the drop down list.
   //If it is than set that to be selected.
   while(i<oScale.options.length){
		if(Scale == oScale.options[i].value){
			oScale.options[i].selected = true;
			break;
		}
		i++;
	}
	//Otherwise set the selected to be the empty one
	if(i==oScale.options.length) {
		oScale.options[0].selected = true;
	}

   txtscale.value=Scale + '%';

   //UPDATING UNITS
   if(oUnitsSel.options.length > 0)
      oUnitsSel.options[scanControl.OutputUnits-1].selected = true;

   //UPDATING ASPECT LOCK

   if(scanControl.SelectionAspectLock){
      owd.disabled = true;
      oht.disabled = true;
      oScale.disabled = true;
     txtscale.disabled = true;
   } else {
      owd.disabled = false;
      oht.disabled = false;
      oScale.disabled = false;
     txtscale.disabled = false;
   }

   if (scanControl.SelectionAspectLock && lockOn.style.display == "none") {
	   lockOff.style.display= "none";	// hide
	   lockOn.style.display= "";		// show
   }
   else if (!scanControl.SelectionAspectLock && lockOff.style.display == "none") {
	   lockOff.style.display= "";		// show
	   lockOn.style.display= "none";	// hide
   }
   
   if(!scanControl.SelectionMade) {
      swd.disabled = true;
      sht.disabled = true;
   } else {
      swd.disabled = false;
      sht.disabled = false;
   }
}

function fnUnits(value) {
   scanControl.OutputUnits=Units[value];
   if (!is_ie4) fnPersistUnitSave(oUnitsSel, "oXMLStoreUnit", value); 
}

function scChange(value)  {
   scanControl.PercentScale = value;
}

function fnLockdim()  {
   scanControl.SelectionAspectLock = !scanControl.SelectionAspectLock;  
}

///////////////////////////////////////////////////////////////////////
////        External Function (called by container App)            ////
///////////////////////////////////////////////////////////////////////

///////////////////
// exOnPreview
// This function is being call externally, if the name gets change
// need to inform the frame window code.
function exOnPreview()
{
   // Set a timer to call preview instead of calling it directly. This has the
   // side effect of causing the browser to update element sizes, which is
   // needed in order to set the size of the scanControl (see fnLaunchPreview).
   setTimeout('fnLaunchPreview();', 0);
   imgScanButton.alt = window.external.AcceptTooltip;  //this will be dynamic
}

//////////////
// exPreShowUI
// This function is being call externally, if the name gets change
// need to inform the frame window code.
function exPreShowUI()
{
   
   //alert('Twain name = ' + window.external.TwainAppName);
   //Might want to use the return string of window.external.TwainAppName
   // and updated it in the progress bar.

   ScanMode = window.external.Mode;
//   DotIsDecimal = decptIsDot();
// HACK HACK HACK
// decptIsDot() is broken, just use Americanized decimal points
	DotIsDecimal = true;


	// Begin of Smart Friends
	if(window.external.AllTopicsEnabled == 1) { 
		//Disable the Enabled menu item
		ensf.style.color = "#778899";
		ensf.style.cursor = "default";
	}
	else {
		//Enable the Enabled menu item
		ensf.style.color = "#000000";
		ensf.style.cursor = "hand";
	}

	if(window.external.AllTopicsDisabled == 1) {
		//disable the Disable menu item
		dissf.style.color = "#778899";
		dissf.style.cursor = "default";
	}
	else {
		//Enabled the Disable menu item
		dissf.style.color = "#000000";
		dissf.style.cursor = "hand";
	}
	// End of Smart Friends

	//If there is no user's manual than disable the menu item.
   if(window.external.UserManualAvailable ==0) {
   		 manual.style.display = "none";
	     manual.style.color = "#778899";
	     manual.style.cursor = "default";
	}

   if( ScanMode  == 1) {  //document mode
      pal['resolution'].grayOut(); //resolution
      resol.style.color = "#778899";     
      img0id.style.display = "none";
      img1id.style.display = "none";
      img2id.style.display = "none";
      img3id.style.display = "none";
      img5id.style.display = "none";
      img6id.style.display = "none";
      glass.style.color = "#778899";
      glass.style.cursor = "default";
      slides.style.color = "#778899";
      slides.style.cursor = "default";
      neg.style.color = "#778899";
      neg.style.cursor = "default";
      //ie 5.0 fix
      outtitle.style.display = "block"; 
      outtitle.style.color = "#778899";           
      basictitle.style.display = "block";
      helptitle.style.display = "block";
      advtitle.style.display = "block";
      scantitle.style.display = "block"; 
      outtitle.style.cursor = "default"; 
      outtitle.onclick = null;
      
                  
   } 
   else { //image mode
      //ie 5.0 fix
      outtitle.style.display = "block";            
      basictitle.style.display = "block";
      helptitle.style.display = "block";
      advtitle.style.display = "block";
      scantitle.style.display = "block";                       
      GlassOrTMA();
   }

   //Setting the radio button based on the preference setting.
   if(scanControl.Preference.EnhancedColor) {
     radioAdvancedColor.checked = true;
	 radioNormalColor.checked = false;
   }
   else {
	radioNormalColor.checked = true;
	radioAdvancedColor.checked = false;
   }

   if (!is_ie4) fnPersistUnitLoad(oUnitsSel, "oXMLStoreUnit"); //Loading persistent for  units
   ckXpaReady();   
   window.external.SetDefaultWidth(535);   
} 

function GlassOrTMA() {
   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true) {
     //Disabling descreen because we are in negatives or slides mode.
     descreenobj.className="title-grayed";
     button_grayout('descreenOff');
     button_grayout('descreenOn');
     des.style.color = "#778899";
     //Disabling the black and white levels sliders.  If we are in XPA mode.
     whtlvltitle.style.display = "none";
     whtlvlslider.style.display = "none";
     blcklvltitle.style.display = "none";
     blcklvlslider.style.display = "none";
     //Disabling the eyedroppers.
     highlightdropper.style.visibility = "hidden";
     shadowdropper.style.visibility = "hidden";
     //Setup the min and max of the slider values
     highlights.min = "-100";
     highlights.max = "100";
     midtone.min = "-100";
     midtone.max = "100";
     shadow.min = "-100";
     shadow.max = "100";
     highlightEntry.maxLength = "4";
	  midtoneEntry.maxLength = "4";
	  shadowEntry.maxLength = "4";
   }
   else {
      //Disabling the black and white levels sliders.  If we are in XPA mode.
      whtlvltitle.style.display = "block";
      whtlvlslider.style.display = "block";
      blcklvltitle.style.display = "block";
      blcklvlslider.style.display = "block";
      //Disabling the eyedroppers.
      highlightdropper.style.visibility = "visible";
      shadowdropper.style.visibility = "visible";
      //Setup the min and max of the slider values for Glass scan
      highlights.min = "0";
      highlights.max = "255";
      midtone.min = "0";
      midtone.max = "255";
      shadow.min = "0";
      shadow.max = "255";
		highlightEntry.maxLength = "3";
   	midtoneEntry.maxLength = "4";
	   shadowEntry.maxLength = "3";
	   des.style.color = "#000000";
   }

}
function ckXpaReady()
{
	if(ScanMode == 1)
	{
   glass.style.color = "#778899";
   glass.style.cursor = "default";
   slides.style.color = "#778899";
   slides.style.cursor = "default";
   neg.style.color = "#778899";
   neg.style.cursor = "default";
	}
	else if((ScanMode == 0) && (scanControl.XpaReady == true))
	{
		glass.style.color = "#000000";
   	glass.style.cursor = "hand";
   	slides.style.color = "#000000";
   	slides.style.cursor = "hand";
   	neg.style.color = "#000000";
   	neg.style.cursor = "hand";
   }
   else if((ScanMode == 0) && (scanControl.XpaReady == false))
   {
   	glass.style.color = "#778899";
   	glass.style.cursor = "default";
   	slides.style.color = "#778899";
   	slides.style.cursor = "default";
   	neg.style.color = "#778899";
   	neg.style.cursor = "default";
	}
   if(scanControl.XpaReady == true && window.external.Mode == 0)   
   {
      glass.style.visibility = "visible";
      slides.style.visibility = "visible";
      neg.style.visibility = "visible";
   }
   ckTMAstate();
   
}

// -- check the scan source of the TMA -- //
function ckTMAstate()
{
	
   if(scanControl.XpaScanEnabled == false)  
   { 		
		
			selimgg.style.visibility = "inherit";
 	  		selimgs.style.visibility = "hidden";
 	  		selimgn.style.visibility = "hidden";
 	  	
   }
   else if(scanControl.XpaScanEnabled == true && scanControl.PhotographicNegative == false) 
   {
   	
      	selimgg.style.visibility = "hidden";
 	   	selimgs.style.visibility = "inherit";
 	   	selimgn.style.visibility = "hidden";
 	   
   }
   else if(scanControl.XpaScanEnabled == true && scanControl.PhotographicNegative == true)
   {
   	
      	selimgg.style.visibility = "hidden";
 	   	selimgs.style.visibility = "hidden";
 	   	selimgn.style.visibility = "inherit";
 	   
    
      //AutoColor will always be true if we are scanning negatives.	
      //The bottom line overwrite the settings in the preferences.
     scanControl.AutoColorEnabled = true;
   }
}   
   
function fnEvalHighlightsSlider(val) {
   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
      scanControl.Highlight =  Math.round(200*val-100);
   else
      scanControl.Highlight =  Math.round(65535*val);
}
function fnEvalMidtoneSlider(val) {
   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
      scanControl.MidtoneGamma = Math.round(200*val-100);
   else
      scanControl.MidtoneGamma = (1+3*val);
}
function fnEvalShadowSlider(val){
   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
      scanControl.Shadow =  Math.round(200*val-100);
   else
      scanControl.Shadow =  Math.round(65535*val);
}
// subtracting 0 means changing the val to be an integer.  I
// am just making sure I am passing an integer to the scanControl
function fnEvalHighlightsEdit(val) {

	//Check to see if it is a number, if not then don't do anything.
	var x = val - 0;
	if(isNaN(x)){
		highlightEntry.select();
		return;
	}

   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
      scanControl.Highlight = (val-0);
   else
      scanControl.Highlight = (257*(val-0));
}
function fnEvalMidtoneEdit(val) {

	//Check to see if it is a number, if not then don't do anything.
	var x = val - 0;
	if(isNaN(x)){
		midtoneEntry.select();
		return;
	}

   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
      scanControl.MidtoneGamma = (val-0);
   else
      scanControl.MidtoneGamma = (val-0);
}
function fnEvalShadowEdit(val){
	//Check to see if it is a number, if not then don't do anything.
	var x = val - 0;
	if(isNaN(x)){
		shadowEntry.select();
		return;
	}

   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
      scanControl.Shadow = (val-0);
   else
      scanControl.Shadow = (257*(val-0));
}

///////////////////////////////////////////////////////////////////////
////       General Utility Functions used throughout scan.js       ////
///////////////////////////////////////////////////////////////////////

// usage: pushSelectOptions("selectID", <option1>, "option2", ...)
function pushSelectOptions(){
   for(var i = 1; i < arguments.length; i++)
   {
      var oOption = document.createElement("OPTION");
      oOption.text = arguments[i].innerText;
      oOption.value = i-1;
      oOption.style.visibility="hidden";
      arguments[0].add(oOption);
   }
}

// Expand/Collapse Objects via style.display
function fnToggleDisplay(id){
   var tmp = null;
   tmp = "document.all." + id;
   obj = eval(tmp);
   obj.style.display = (obj.style.display != "block" ? "block" : "none");
   UpdateExpLevel();
}

//-- trap and kill unwanted keystrokes -----//

function killkeys()
{
    var key = event.keyCode;   	
    if ((event.ctrlKey && key == 78) || (event.ctrlKey && key == 80) || (event.ctrlKey && key == 65))
    { 	
    	 event.returnValue = false;  
    	 event.keyCode = 0;
       event.cancelBubble = true;
       return false;
    }
    else if (key==116 || key == 113 || key == 114 || key == 115 || key == 117 || key == 118 || key == 121 || key == 123) //kill function keys
    {    
        event.keyCode = 0;
        event.cancelBubble = true;
        return false;
    }
}


//MOVE THIS FN TO GLOBAL
///////////////////////////////////////////////
////////////  range validator. 
function fnRangeValidate(value, min, max, def, prec) {
   value = VBfmtnum( (isNaN(parseFloat(value))? def : parseFloat(value)), prec ) ;
   if ( value<=min ) value=min;
   if ( value>=max ) value=max;
   return VBfmtnum(value, prec);
}
function fnValidateVal(name, value) {
   if(value == "") {
      switch(name.id) {
         case "swd": //selection width
          if ((Units[oUnitsSel.value] == 1) || ( Units[oUnitsSel.value] ==2))
            value = VBfmtnum(scanControl.SelectionWidth, 2);
         else if (Units[oUnitsSel.value] == 3)
            value = VBfmtnum(scanControl.SelectionWidth, 1);
         else
            value = VBfmtnum(scanControl.SelectionWidth, 0);
         break;
         case "sht": //selection height
          if ((Units[oUnitsSel.value] == 1) || ( Units[oUnitsSel.value] ==2))
            value = VBfmtnum(scanControl.SelectionHeight, 2);
         else if (Units[oUnitsSel.value] == 3)
            value = VBfmtnum(scanControl.SelectionHeight, 1);
         else
            value = VBfmtnum(scanControl.SelectionHeight, 0);
         break;
         case "owd": //output width
          if ((Units[oUnitsSel.value] == 1) || ( Units[oUnitsSel.value] ==2))
            value = VBfmtnum(scanControl.OutputWidth, 2);
         else if (Units[oUnitsSel.value] == 3)
            value = VBfmtnum(scanControl.OutputWidth, 1);
         else
            value = VBfmtnum(scanControl.OutputWidth, 0);
         break;

         case "oht": //output height
          if ((Units[oUnitsSel.value] == 1) || ( Units[oUnitsSel.value] ==2))
            value = VBfmtnum(scanControl.OutputHeight, 2);
         else if (Units[oUnitsSel.value] == 3)
            value = VBfmtnum(scanControl.OutputHeight, 1);
         else
            value = VBfmtnum(scanControl.OutputHeight, 0);
         break;
       case "txtresolution":
         value = scanControl.FinalResolution;
         break;
      }
   } else {
 		//If not decimal = comma
	   if(!DotIsDecimal){ 
			var num = new String(value);
			var val1 = num.replace(",", ".");
			value = (val1 - 0);
	   }
   }
   return (value-0);
}

function fnNoChar(){
	if (event.keyCode < 48 || event.keyCode > 57)
		  return false;
}
function fnChckChar(){
   if(!DotIsDecimal){ 
     //44 is a comma
	   if ((event.keyCode != 44) && (event.keyCode < 48 || event.keyCode > 57))
		  return false;
   } else {
	 //46 is a period.
	   if ((event.keyCode != 46) && (event.keyCode < 48 || event.keyCode > 57))
		  return false;
   }	  
}
function fnChckCharwithPercent(){
   //37 is a %.  It will let you type in %.
   if ((event.keyCode != 37) && (event.keyCode < 48 || event.keyCode > 57))
      return false;
}
function fnChckDatchChar(){
   //45 is a minus or datch.
   //alert(event.keyCode);
   if ((event.keyCode != 45) && (event.keyCode < 48 || event.keyCode > 57))
      return false;
}
function fnHSChckChar() {
   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
		return fnChckDatchChar();
	else
		return fnNoChar();
}

function fnMidtoneChckChar() {
   if(scanControl.XpaScanEnabled == true || scanControl.PhotographicNegative == true)
		return fnChckDatchChar();
	else
		return fnChckChar();
}
