﻿var hasChenged = false;
var imgX = 0;
var imgY = 0;
var mX = 0;
var mY = 0;
var offsetLeft = 310;
var offsetTop = 50;
var myWidth = 0;
var myHeight = 0;
var scaleOffsetX, dragOffsetX = 0, zOffsetX = 0; 
var scaleOffsetY, dragOffsetY = 0, zOffsetY = 0;
var imgSrc = '';
var mode = 'A'; // A = add, M = move, Z = zoom, S = Simbad object
var lastMode = 'A';
var cellHeight;
var cellWidth;
var sessionID;
var tiles;
var canvasDefHTML, mapDefHTML;
var zoom = 0;
var iTimeoutId = null;
var iLoadID = null;
var iInfo = null;
var colorID;
var FITSw, FITSh, tileRows, tileCols, imgs;
var selStar = '', selStarMapName = '';
var cZoomX = new Array();
var cZoomY = new Array();
var nTiles;
var thumbStartX, thumbStartY, selStartX, selStartY;
var dblClick=false;
var dblMode=0;
var navTo; // 0 = header, 1 = report, 2 = details
var state;
var ignoreImgClick=false;
var startup=true;
var measInList=0;
var _cX = 0, _cY=0, _Rad=0; // remember position of red circe, magnification
var mainMode = 0; // 0 = regular, 1 = pixel
var lastMagSel='';
var uidShowed = false;

window.onerror = handleError;

// ***********************************
// ******** GENERAL FUNCTIONS ********
// ***********************************

function a(name) {
  return document.getElementById(name);
};

function StartLoading() {
  colorID = 0;
  iLoadID = setTimeout('ChangeColor()', 300);
  a('divLoad').style.visibility = 'visible';
};

function ChangeColor() {
  colorID++;
  var divstyle = a('divLoad').style;
  if (colorID==2) {
    divstyle.backgroundColor = 'DarkBlue';
    colorID = 0;
  } else {
    divstyle.backgroundColor = 'Blue';
  }
  iLoadID = setTimeout('ChangeColor()', 300);
};

function CancelLoading() {
  window.clearTimeout(iLoadID);
  a('divLoad').style.visibility = 'hidden';
};

function setCursor(curType) {
  var divImg = a('canvas');
  divImg.style.cursor = curType;
};

function handleError() {
	return true;
};


function infoChanged() {
 hasChenged = true;
 a('btnOK').style.color='blue';
};

function OnError(result) {
  CancelLoading();
  alert(result.get_message());
};

function startSingleClick()
{
  iTimeoutId = setTimeout('clickOnImage()', 250);
};

function startDblClick(CancelSingle)
{
  dblClick = true;
  if (iTimeoutId) window.clearTimeout(iTimeoutId);
  ZoomIn();
};

function SetMode(newmode) {
  mode = newmode;
  var obj = a('spOnClick');
  if(mode == 'Z') {
    obj.innerHTML = 'Magnify';
  } if(mode == 'A') {
    obj.innerHTML = 'Photometry';
  } if(mode == 'S') {
    obj.innerHTML = 'SIMBAD Info';
  }
};

function focus(name) {
	if (a(name)) {
		a(name).focus();
		a(name).select();
	}
};

function ClearSelect(sel) {
  for(var count = sel.options.length - 1; count >= 0; count--)
    sel.options[count] = null;
};

function IsNumeric(sText) {

   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
};

//***********************************
//******** COOKIES ******************
//***********************************

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
};

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
};

function eraseCookie(name) {
	createCookie(name,"",-1);
};

function eraseCookies() {
	eraseCookie('PHM_X');
	eraseCookie('PHM_Y');
	eraseCookie('PHM_Names');
	eraseCookie('PHM_Type');
	eraseCookie('PHM_InnerAn');
	eraseCookie('PHM_Width');
	eraseCookie('PHM_Ap');
	eraseCookie('PHM_SNR');
	eraseCookie('PHM_FWHM');
};

function eraseCookiesSIMBAD() {
	eraseCookie('SIMBAD_X');
	eraseCookie('SIMBAD_Y');
	eraseCookie('SIMBAD_Names');
};

function eraseCookiesUnidentified() {
	eraseCookie('UID_X');
	eraseCookie('UID_Y');
	eraseCookie('UID_Names');
};

//***********************************
//******** INITIALISATION ***********
//***********************************

function InitAnalysis() {

  canvasDefHTML = '';
  var el = a("divMap"); 
  mapDefHTML = el.innerHTML;
  
  var el = a("canvas"); 
  if (el.addEventListener){
    el.addEventListener('mousemove', movePointerInfo, false); 
  } else if (el.attachEvent){
    el.attachEvent('onmousemove', movePointerInfo);
  } 
  
  LoadStateFromCookie();
  resize();
  
  var dragable1 = DragHandler.attach(a('canvas'));
	dragable1.dragBegin = beginDrag;
	dragable1.drag = dragging;
	dragable1.dragEnd = endDrag;
	
	var dragable2 = DragHandler.attach(a('divThumbZoom'));
	dragable2.dragBegin = beginDragZoom;
	dragable2.drag = draggingZoom;
	dragable2.dragEnd = endDragZoom;
          
  var hid = a('hidImgSrc');
  if(hid.value == '0') 
    LoadImage();
  else
  {
    // Images is cached, no need to re-load
    SetUpImage(false);
    PageMethods.w20(c20,OnError);
  }
  
  hid = a('hidSeqName');
  if(hid.value != '0') {
    var sX = readCookie('PHM_X');
    if(sX == null) {
      a('ddlSeq2').value = hid.value;
      LoadSequence();
    }
  }
  
  // Draw Nort-East
  var jg2 = new jsGraphics("divPA");
  jg2.clear();
  jg2.setFont("arial","10px",Font.BOLD);
  jg2.setStroke(2);
  jg2.setColor("darkblue");
  
  hid = a('hidPA_N');
  var c = new Array();
  c = hid.value.split(',');
  var xN = 1*c[0];
  var yN = 1*c[1];
  var txN = 1*c[2];
  var tyN = 1*c[3];
  
  hid = a('hidPA_E');
  c = hid.value.split(',');
  var xE = 1*c[0];
  var yE = 1*c[1];
  var txE = 1*c[2];
  var tyE = 1*c[3];
  
  var low;
  if(tyN > tyE) 
    low = tyN;
  else
    low = tyE;
  
  var offsetx = 30;
  var offsety = 30 + low;
  jg2.drawLine(offsetx,offsety,offsetx+xN,offsety-yN); 
  
  jg2.drawString("N",offsetx+txN,offsety-tyN);  
  jg2.drawLine(offsetx,offsety,offsetx+xE,offsety-yE); 
  jg2.drawString("E", offsetx+txE,offsety-tyE);
  jg2.paint();
  
  var jg3 = new jsGraphics("divScale");
  jg3.clear();
  jg3.setFont("arial","10px",Font.BOLD);
  jg3.setStroke(2);
  jg3.setColor("darkblue");
  
  hid = a('hidScale');
  var l = 1*hid.value;
  jg3.drawLine(10,60,l+10,60); 
  jg3.drawLine(10,60-2,10,60+2); 
  jg3.drawLine(l+10,60-2,l+10,60+2); 
  jg3.drawString("1 arc min", 10,40);
  jg3.paint();
  
  startup = false;
  
};

function c20(r) {
	
	// Loaded from session canvas state
  var hidImgSrc = a('hidImgSrc');
  hidImgSrc.value = r;

  var p = new Array();
  p = r.split('|');
  
  canvasDefHTML = p[0];
  a('canvas').innerHTML = canvasDefHTML ;
  a('tblWait').style.visibility = 'hidden';
  a('divHide').style.visibility = 'visible';
  a('divMenu').style.visibility = 'visible';
  a('divMCat').style.visibility = 'visible';
  a('divMTools').style.visibility = 'visible';
  SetUpImage(false);
};

function LoadStateFromCookie() {
  var ap = readCookie('ap');
  if(ap==null) ap = '5'; // default
  ap = ap.replace(',','.');
  if(isNaN(parseInt(a('txtAp').value))) a('txtAp').value = ap;
  var ir = readCookie('ir');
  if(ir==null) ir = 10; // default
  a('txtInnerAn').value = ir;
  a('txtInnerAn2').value = ir;
  var aw = readCookie('aw');
  if(aw==null) aw = 10; // default
  a('txtWidth').value = aw;
  a('txtWidth2').value = aw;
  // Load settings
  var minSNR = readCookie('minSNR');
  if(minSNR==null) minSNR = '20'; // default
  var searchRad = readCookie('searchRad');
  if(searchRad==null) searchRad = '5'; // default
  a('txtMinSNR').value = minSNR;
  if(isNaN(parseInt(a('txtSR').value))) a('txtSR').value = searchRad;
  //a('txtSR').value = searchRad;
  
  var infoOnClick = readCookie('infoOnClick');
  if(infoOnClick==null) infoOnClick = 'true';
  if(infoOnClick=='true') {
    a('rClick').checked = true;
    a('rOver').checked = false;
  } else {
    a('rClick').checked = false;
    a('rOver').checked = true;
  }
};

//***********************************
//******** DISPLAY ******************
//***********************************

function ShowDiv(name, show) {
  HideSubMenu('divMToolsSub');
  HideTools();
  var div = a(name);
  if(show)
    div.style.visibility='visible';
  else
    div.style.visibility='hidden';
};

function HideTools() {
  a('divAperture').style.visibility='hidden';
  a('divSettings').style.visibility='hidden';
  a('divDisplay').style.visibility='hidden';
  a('divDblMeas').style.visibility='hidden';
};

function seqStat(enable) {
  // Toggle mag or color display
  var seq = a('divSeq');
  var col = a('divColor');
  if(!enable) {
    seq.style.visibility='visible';
    col.style.visibility='hidden';
    seq.style.height='20px';
    col.style.height='0px';
  } else {
    seq.style.visibility='hidden';
    col.style.visibility='visible';
    seq.style.height='0px';
    col.style.height='20px';
  };
};

function hidePosInfo() {
  obj = a('posInfo').style;
  obj.visibility = 'hidden';
};

function resize() {

  windowSize();
  var style;
  var div = a("border");  
  div.style.height = (1*myHeight - div.offsetTop - 5) + "px";
  div.style.width = (1*myWidth - div.offsetLeft - 10) + "px";
  var borderLeft = div.style.left;
  var borderWidth = div.style.width;
  var top = div.style.top;
  
  style = a("divScale").style;  
  style.top = (1*myHeight - 80) + 'px';
  style.left = borderLeft;
  
  style = a("divPA").style;  
  style.top = (1*myHeight - 80) + 'px';
  style.left = (1*myWidth - 75 - 10) + 'px';
  
  style = a("divLoad").style;  
  style.top = (1*myHeight - 30) + 'px';
  style.left = (1*myWidth - 130 - 10) + 'px';
    
  style = a("divTop").style;  
  style.width = style.width;
  
  style = a("divMag").style;  
  style.width = (1*myWidth - 15) + "px";
  style.height = (1*myHeight - 55) + "px";
  
  style = a("divPan").style;  
  style.top = (1*myHeight - 205) + 'px';
  
  style = a("divStars").style;  
  style.height = (1*myHeight - parseInt(style.top) - 215) + 'px';
  
  ResizeMeaslist();
  
  // position and size tool divs
  var toolLeft = (1*myWidth - 270 - 10) + 'px';
  var toolWidth = '270px';
  var toolHeight = '220px';
  PosDivTool('divDisplay',top,toolLeft,toolWidth,toolHeight);
  PosDivTool('divAperture',top,toolLeft,toolWidth,toolHeight);
  PosDivTool('divSettings',top,toolLeft,toolWidth,toolHeight);
  PosDivTool('divDblMeas',top,toolLeft,toolWidth,toolHeight);
  
  // Position menues
  style = a('divMCat').style;
  style.top = '8px';
  style.left = (1*myWidth - 350) + 'px';
  style = a('divMTools').style;
  style.top = '8px';
  style.left = (1*myWidth - 260) + 'px';
  
  // Position sub menus
  style = a('divMCatSub').style;
  style.top = '31px';
  style.left = (1*myWidth - 350) + 'px';
  style = a('divMToolsSub').style;
  style.top = '31px';
  style.left = (1*myWidth - 260) + 'px';
  
  if(!startup) {
    ResizeThumbMap();
    PositionThumbMap(0,0); 
  }
};

function windowSize() {

  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
};

function ShowSubMenu(name) {
  a('divMCatSub').style.visibility='hidden';
  a('divMToolsSub').style.visibility='hidden';
  a(name).style.visibility='visible';
};

function HideSubMenu(name) {
  a(name).style.visibility='hidden';
};

function PosDivTool(name,top,left,width,height) {
  var style = a(name).style;
  style.top = top;
  style.left = left;
  style.width = width;
  style.height = height;
};

function ShowMeasTable(show) {
  var tbl = a('divMeasures').style;
  var empty = a('divNoMeas').style;
  if(show) {
    tbl.visibility = 'visible';
    tbl.height = '250px';
    empty.visibility = 'hidden';
    empty.height = '0px';
  } else {
    tbl.visibility = 'hidden';
    tbl.height = '0px';
    empty.visibility = 'visible';
    empty.height = '250px';
  }
};

function ShowPixelMode() {
  mainMode = 1;
  a('divMenu').style.visibility = 'hidden';
  a('divMCat').style.visibility = 'hidden';
  //a('divMTools').style.visibility = 'hidden';
  a('divMenPixel').style.visibility = 'visible';
  var div = a('divMag');
  div.style.visibility = 'visible';
  var scX = FITSCoordFromWinCoordX(mX);
  var scY = FITSCoordFromWinCoordY(mY);
  lastMagSel = '';
  _cX = 0;
  _cY = 0;
  _Rad = 0;
  PageMethods.w13(scX,scY,parseInt(div.style.width),parseInt(div.style.height),c13,OnError);
};

function ShowMeasDiv(show) {
  var obj = a('popInfo').style;
  var col = a('divColor').style;
  var seq = a('divSeq').style;
  if(show) {
    obj.visibility = 'visible';
    col.visibility = 'visible';
    seq.visibility = 'visible';
  } else {
    obj.visibility = 'hidden';
    col.visibility = 'hidden';
    seq.visibility = 'hidden';
  }
};

//***********************************
//******** NAVIGATION ***************
//***********************************

function SaveCanvas(target) {
  navTo = target;
  // Used for cahcing (cause of navigation between pages)
  state = FITSh + '|' + FITSw + '|' + sessionID + '|' + cellHeight + '|' + cellWidth + '|' + tileRows + '|' + tileCols + '|' + a('sImgInfo').innerHTML + '|' + a('hidIndex').value + '|' + imgs + '|' + zoom + '|' + mainMode + '|' + mode;
  PageMethods.w21(canvasDefHTML,state,c21,OnError);
};

function c21() {
  switch(navTo) {
    case 0:
      window.location.href = 'FITSHeader.aspx';
      break;
    case 1:
      var ap = a('txtAp').value;
      var seqName = '';
      if(a('ddlSeq2').selectedIndex > -1) seqName = a('ddlSeq2').options[a('ddlSeq2').selectedIndex].text;
      var sr = a('txtSR').value;
      var minSNR = a('txtMinSNR').value;
      window.location.href = 'SingleImageReport.aspx?create=1&ap=' + ap + '&seq=' + seqName + '&sr=' + sr + '&minsnr=' + minSNR;
      break;
    case 2:
      var ap = a('txtAp').value;
      var name = a('hidMapName').value;
      window.location.href = 'MeasurementInfo.aspx?ap=' + ap + '&star=' + selStar;
      break;
    case 3:
      window.location.href = '../Help/AnalyseImage.aspx';
      break;
  }
};

function NextImage() {
  StartLoading();
  var i = a('hidIndex').value;
  PageMethods.w17(i,c17,OnError);
};

function PrevImage() {
  StartLoading();
  var i = a('hidIndex').value;
  PageMethods.w18(i,c17,OnError);
};

function c17(r) {
	// Next and previous image
  if(r!='') {
  
    var p = new Array();
    p = r.split('|');
    
    a('hidIndex').value = p[0];
    a('txtLow').value = p[3];
    a('txtHigh').value = p[4];
    
    // Refresh the sequence
    var ap = a('txtAp').value.replace(',','.');
    var ia = a('txtInnerAn').value;
    var w = a('txtWidth').value;
    var sr = a('txtSR').value;
    PageMethods.w19(ap,ia,w,sr,c19,OnError);
 
  }
};

function c19(r) {
	// Sequence refreshed after image navigation
  if(r!='') {
    var p = new Array();
    p = r.split('|');
    SeqToCookies(p);
  }
  ReLoadImage();
};

//***********************************
//******** IMAGE DRAGGING ***********
//***********************************

function PositionThumbMap(x, y) {
  var divThumbZoom = a('divThumbZoom');
  var divThumb = a('divThumb');
  if(x==0 && y==0) {
    // Startup
    thumbStartX = 0.5*(parseInt(divThumb.style.width) - parseInt(divThumbZoom.style.width));
    divThumbZoom.style.left = thumbStartX + 'px';
    thumbStartY = 0.5*(parseInt(divThumb.style.height) - parseInt(divThumbZoom.style.height));
    divThumbZoom.style.top = thumbStartY + 'px';
  } else {
    // Dragging
    var dW = parseInt(divThumb.style.width) / (zoom*FITSw);
    var dH = parseInt(divThumb.style.height) / (zoom*FITSh);
    divThumbZoom.style.left = (thumbStartX - dW*x) + 'px';
    divThumbZoom.style.top = (thumbStartY - dH*y) + 'px';
  }
};

function PositionCanvas(x, y) {

  var divThumb = a('divThumb');
  var divBorder = a('border');
  var divCanvas = a('canvas');
  
  // Dragging
  var dW = (zoom*FITSw) / parseInt(divThumb.style.width);  
  var dH = (zoom*FITSh) / parseInt(divThumb.style.height);
  divCanvas.style.left =(0.5*(zoom*FITSw - parseInt(divBorder.style.width)) - dW*x) + 'px';
  divCanvas.style.top = (0.5*(zoom*FITSh - parseInt(divBorder.style.height)) - dH*y) + 'px';
  if (selStartX && selStartY) {
    var img = a('iSelLarge').style; 
    img.left = (selStartX + (0.5*(zoom*FITSw - parseInt(divBorder.style.width)) -dW*x)) + 'px';
    img.top = (selStartY + (0.5*(zoom*FITSh - parseInt(divBorder.style.height))-dH*y)) + 'px';
  }
};

function beginDrag (element, x, y) {
	if(mode != 'M') lastMode = mode;
};

function dragging (element, x, y) {
  // Drag the image
  mode = 'M';
  setCursor('move');
  PositionThumbMap(x/zoom,y/zoom);
  var img = a('iSelLarge').style; 
  if(selStartX && selStartY) {
    img.left = (selStartX + x) + 'px';
    img.top = (selStartY + y) + 'px';
  }
  var el = a('showInfoDec'); 
  el.innerHTML = 'X: ' + x + ' Y: ' + y;
};

function endDrag (element, x, y) {
  // Release drag image
	if(mode=='M') {
	  dragOffsetX = x;
	  dragOffsetY = y;
	}
	renderTiles();
	setCursor('crosshair');
};

function beginDragZoom (element, x, y) {
  //
};

function draggingZoom (element, x, y) {
  // Drag on the overview image
  PositionCanvas(x,y);
};

function endDragZoom (element, x, y) {
	// End drag on the overview image
	var divThumb = a('divThumb');
  var divBorder = a('border');
  var divCanvas = a('canvas');
  var dW = (zoom*FITSw) / parseInt(divThumb.style.width);  
  var dH = (zoom*FITSh) / parseInt(divThumb.style.height);
	dragOffsetX = parseInt(divCanvas.style.left);
	dragOffsetY = parseInt(divCanvas.style.top);
	renderTiles();
	setCursor('crosshair');
};

//***********************************
//******** ZOOMING ******************
//***********************************

function ZoomIn() {
  
  if(zoom<8) {
  
    zoom *= 2;
    //a("spZoom").innerHTML = 'Zoom factor: ' + zoom;
      	
    var div = a("border");  
    var cY = (1*myHeight - div.offsetTop) / 2;
    var cX = (1*myWidth - div.offsetLeft) / 2;
    
    div = a("canvas");  
    cZoomX.push(div.style.left);
  	cZoomY.push(div.style.top);
  	
    zOffsetX = parseInt(div.style.left) + (cX - (mX - offsetLeft));
    zOffsetY = parseInt(div.style.top) + (cY - (mY - offsetTop));
    
	  div.style.left = parseInt(div.style.left) + zOffsetX + 'px';
	  div.style.top = parseInt(div.style.top) + zOffsetY + 'px';
  	  	
	  dragOffsetX = parseInt(div.style.left);
		dragOffsetY = parseInt(div.style.top);
  	
    ClearCanvas();
    SetUpImage(true);
    ResizeThumbMap();
    
  }
};

function ZoomOut() {

  if(zoom > 0.25) {
  
    zoom /= 2;
    div = a("canvas");  
    if (cZoomX.length == 0) {
      div.style.left = Math.round(parseInt(div.style.left)/2) + 'px';
	    div.style.top = Math.round(parseInt(div.style.top)/2) + 'px';
	  } 
	  else {
	    div.style.left = cZoomX.pop();
	    div.style.top = cZoomY.pop();
	  }
	  dragOffsetX = parseInt(div.style.left);
		dragOffsetY = parseInt(div.style.top);
    ClearCanvas();
    SetUpImage(true);
    ResizeThumbMap();
    
  }
};

function ResizeThumbMap() {
  var divThumb = a('divThumb');
  var divThumbZoom = a('divThumbZoom');
  var winWidth = (1*myWidth - offsetLeft - 10);
  var winHeight = (1*myHeight - offsetTop - 5);
  var dW = winWidth / (zoom*FITSw);
  var dH = winHeight / (zoom*FITSh);
  divThumbZoom.style.width = parseInt(divThumb.style.width) * dW + 'px';
  divThumbZoom.style.height = parseInt(divThumb.style.height) * dH + 'px';
  var oElem = a('canvas');
  var x = parseInt(oElem.style.left)/zoom;
	var y = parseInt(oElem.style.top)/zoom;
	PositionThumbMap(x,y);
};

//***********************************
//******** IMAGE RENDERING **********
//***********************************

function Histogram() {
  StartLoading();
  
}

function ClearCanvas() {
  ClearTable();
  var canvas = a("canvas");
  canvas.innerHTML = '';
  canvasDefHTML = '';
  // Reset tiles
  for(y = 0; y < tiles[0].length-1; y++) { //Loop Height
    for(x = 0; x < tiles.length-1; x++) { //Loop Width
      tiles[x][y] = 0;
    }
  }
};

function ReLoadImage() {
  if(mainMode==0) {
    ClearCanvas();
    LoadImage();
  } else {
    RefreshADUTable();
  }
};

function LoadImage() {
  var low = a("txtLow").value;  
  var high = a("txtHigh").value;  
  var imgNbr = a("hidIndex").value;  
  PageMethods.w1(myHeight-offsetTop,myWidth-offsetLeft,low,high,imgNbr,OnImageComplete,OnError);
};

function OnImageComplete(result) {
  var hidImgSrc = a('hidImgSrc');
  hidImgSrc.value = result;
  SetUpImage(true);
};

function SetUpImage(doRender) {

  var hidImgSrc = a('hidImgSrc');
  var p = new Array();
  p = hidImgSrc.value.split('|');
  
  FITSh = 1 * p[1];
  FITSw = 1 * p[2];
  sessionID = p[3];
  cellHeight = 1*p[4];
  cellWidth = 1*p[5];
  tileRows = 1*p[6];
  tileCols = 1*p[7];
  a('sImgInfo').innerHTML = p[8];
  var curimg = 1*p[9];
  imgs = 1*p[10];
  if(zoom==0) zoom = 1*p[11];
  mainMode = 1*p[12];
  mode = p[13];
  
  if(imgs==0) {
    var divNav = a('divNav');
    divNav.style.visibility='hidden';
  } else {
    a('spZoom').innerHTML = 'Zoom factor: ' + zoom;
    a('sImgNbr').innerHTML = 'Image ' + curimg + ' of ' + imgs;
    a('sAp').innerHTML = 'Aperture radius is ' + a('txtAp').value + ' pixels.';
  }
  
  scaleOffsetX = Math.round(0.5*(zoom * FITSw - (myWidth-offsetLeft)));
  scaleOffsetY = Math.round(0.5*(zoom * FITSh - (myHeight-offsetTop)));
    
  tiles = new Array();
  for(y = 0; y < tileRows; y++) { //Loop Height
    var row = new Array();
    for(x = 0; x < tileCols; x++) { //Loop Width
      row[x] = 0;  
    }
    tiles[y] = row;
  }
  
  // Create map
  var divThumb = a('divThumb');
  var divThumbZoom = a('divThumbZoom');
  if(FITSw >= FITSh) {
    divThumb.style.height = parseInt(divThumb.style.width) * (FITSh/FITSw) + 'px';
    if(parseInt(divThumb.style.height) > 150) {
      divThumb.style.width = parseInt(divThumb.style.width)*(150/parseInt(divThumb.style.height)) + 'px';
      divThumb.style.height = '150px';
    }
  } else {
    divThumb.style.width = parseInt(divThumb.style.height) * (FITSw/FITSh) + 'px';
    if(parseInt(divThumb.style.width) > 250) {
      divThumb.style.height = parseInt(divThumb.style.height)*(250/parseInt(divThumb.style.width)) + 'px';
      divThumb.style.width = '250px';
    }
  }
  divThumb.style.left = 0.5*(300 - parseInt(divThumb.style.width)) + 'px';
  
  if(doRender) renderTiles();
  RefreshCanvas();
  ResizeThumbMap();
  PositionThumbMap(0,0); 
      
};
  
function renderTiles() {

  var low = a("txtLow").value;  
  var high = a("txtHigh").value;  
  var winWidth = (1*myWidth - offsetLeft - 10);
  var winHeight = (1*myHeight - offsetTop - 5);
  var i = 0;
  var left, top;
  nTiles = 0;
  for(y = 0; y < tileRows; y++) //Loop Height
  {
     for(x = 0; x < tileCols; x++) //Loop Width
     {         
        if(tiles[y][x] == 0) {
          left = x * zoom * cellWidth - scaleOffsetX + dragOffsetX;
          top = y * zoom * cellHeight - scaleOffsetY + dragOffsetY;
          if(left + zoom * cellWidth > 0 && left < winWidth && top + zoom * cellHeight > 0 && top < winHeight) {
            PageMethods.w14(x,y,cellWidth,cellHeight,zoom,low,high,i,OnTileCreated,OnError);
            tiles[y][x] = 1;
            nTiles = i;
          }
        }
        i = i + 1;
     }
   }
};

function OnTileCreated(result) {
  //alert(result);
  var p = new Array();
  p = result.split('|');
  var divParent = a('canvas');
  addImage(divParent, '../img/' + sessionID + '/' + p[0] + '.jpg', 1*p[1] * zoom * cellWidth - scaleOffsetX, 1*p[2] * zoom * cellHeight - scaleOffsetY);
  if(nTiles == 1*p[0]) {
    // Done loading images, show sequence
    a("tblWait").style.visibility = 'hidden';
    a("divHide").style.visibility = 'visible';
    a("divMenu").style.visibility = 'visible';
    a("divMCat").style.visibility = 'visible';
    a("divMTools").style.visibility = 'visible';
  }
};

function addImage(parentDiv, filename, x, y) {
  var now = new Date();  
  var s = '<IMG style=\"POSITION: absolute; z-index:0; LEFT: ' + x + 'px; TOP: ' + y + 'px; WIDTH: ' + zoom * cellWidth + 'px; HEIGHT: ' + zoom * cellHeight + 'px;\" src=\"' + filename + '?' + now.getTime() + '\" >'; 
  //parentDiv.innerHTML += s;
  var newdiv = document.createElement('div');
  newdiv.innerHTML += s;
  parentDiv.appendChild(newdiv);
  // Keep this to reuse when clearing drawing on the canvas
  canvasDefHTML += s;
};

//***********************************
//*** ADD MEASUREMENT FROM CLICK ****
//***********************************

function clickOnImage() {

  if(ignoreImgClick) {
    ignoreImgClick = false; // reset    
  }
  else {
      
    var scX = FITSCoordFromWinCoordX(mX);
    var scY = FITSCoordFromWinCoordY(mY);
      
    if(dblClick)
      dblClick = false; 
    else if(mode == 'M')
      mode = lastMode;
    else if(mode == 'Z') 
      ShowPixelMode();
    else if(mode == 'S') {
    
      // No measurement, perhaps SIMBAD object
      var found_SIMBAD = false;
      if(!found) {
        var sX_S = readCookie('SIMBAD_X');
        var sY_S = readCookie('SIMBAD_Y');
        if (sX_S != null) {
          var posX_S = new Array();
          var posY_S = new Array();
          posX_S = sX_S.split(',');
          posY_S = sY_S.split(',');
          var d, i;
          for (i=0; i<posX_S.length; i++) {
            d = Math.sqrt(Math.pow(1*posX_S[i] - scX, 2) + Math.pow(1*posY_S[i] - scY, 2));
            if (d < 10) {
              found_SIMBAD = true;
              break;
            }
          }
        }
      }
  	
	    if(found_SIMBAD) {
	      StartLoading();
        var n_S = readCookie('SIMBAD_Names');
        var ns_S = new Array();
        ns_S = n_S.split(',');
        PageMethods.w3(ns_S[i],OnSIMBADClickComplete,OnError);
      }
      
    }
    else if(mode == 'A' || mode == 'D') {
        
      var ap = 1*a('txtAp').value.replace(',','.');
        
      // Check if an existing star is clicked
      var found = false;
      var sX = readCookie('PHM_X');
      var sY = readCookie('PHM_Y');
      if (sX != null) {
        var posX = new Array();
        var posY = new Array();
        posX = sX.split(',');
        posY = sY.split(',');
        var d, i;
        for (i=0; i<posX.length; i++) {
          d = Math.sqrt(Math.pow(1*posX[i] - scX, 2) + Math.pow(1*posY[i] - scY, 2));
          if (d < 2*ap) {
            found = true;
            break;
          }
        }
      }    
      
      var dbl = 0;
      if(mode == 'D') dbl = dblMode;
        
      StartLoading();
      if (found) {  
        var n = readCookie('PHM_Names');
        var ns = new Array();
        ns = n.split(',');
        PageMethods.w4(ns[i],dbl,OnMeasComplete,OnError);
      }
      else {
        var ap = a('txtAp').value.replace(',','.');
        var innerAn = a('txtInnerAn').value;
        var annWidth = a('txtWidth').value;
        var sr = a('txtSR').value;
        PageMethods.w2(scX,scY,ap,innerAn,annWidth,dbl,sr,c2,OnError);
      }
    }
  }  
};

function c2(result) {

  if(result=='Name in use') {
    alert('That name is already in use');
    return false;
  }

  var p = new Array();
  p = result.split('|');
  var X = 1*p[0];
  var Y = 1*p[1];
  var innerAn = a('txtInnerAn').value;
  var annWidth = a('txtWidth').value;
  
  // Append star data to cookies
  MeasToCookie('PHM_X', X);  
  MeasToCookie('PHM_Y', Y);  
  MeasToCookie('PHM_Names', p[3]);
  MeasToCookie('PHM_Type', 2);
  MeasToCookie('PHM_InnerAn', innerAn);
  MeasToCookie('PHM_Width', annWidth);
  MeasToCookie('PHM_SNR', parseInt(p[6]));
  MeasToCookie('PHM_FWHM', p[9]);
  
  var aperture = a('txtAp').value;
  aperture = aperture.replace(',','.');
  var jg = new jsGraphics("canvas");
  drawMeasurement(jg,2,1*X,1*Y,zoom*innerAn,zoom*annWidth,zoom*aperture,p[3],parseInt(p[6]),p[9]);
  jg.paint();
  
  ShowStarInfo(p);
  PlaceSelector(selStar);
  
  var span = a('sNTarget');
  var N = 0;
  if(IsNumeric(span.innerHTML)) 
    N = parseInt(span.innerHTML);
  N++;
  span.innerHTML = N;
   
};

function MeasToCookie(name, value) {
  var cookie = readCookie(name);
  if(cookie == null)
    cookie = value;
  else
    cookie = cookie + ',' + value;
  createCookie(name,cookie,1);
};

//***********************************
//******** DISPLAY STAR INFO ********
//***********************************

function ClickOnSelector() {
  if(mode=='A') {
    StartLoading();
    PageMethods.w4(selStar,0,OnMeasComplete,OnError);
  } else if(mode=='Z')
    ShowPixelMode();
};

function MouseoverSelector() {
  if(mode=='A') {
    if(!a('rClick').checked) {
      StartLoading();
      PageMethods.w4(selStar,0,OnMeasComplete,OnError);
    }
  }
};

function BlankImgAction(name) {
  if(mode=='A') {
    StartLoading();
    PageMethods.w4(name,0,OnMeasComplete,OnError);
  }
};

function OnMeasComplete(result) {
  
  var p = new Array();
  p = result.split('|');
  ShowStarInfo(p);
  PlaceSelector(selStar);
  
};

function ShowStarInfo(p) {
  var obj = a('popInfo').style; 
  obj.left = (mX - 150) + 'px';
  obj.top = (mY -140) + 'px';
  //obj.visibility = 'visible';
  ShowMeasDiv(true);
  var obj = a('txtName'); 
  obj.value = p[3];
  selStar = p[3];
  //obj = a('hidMapName'); 
  //obj.value = p[19]; 
  selStarMapName = p[19];
  obj = a('sIM'); 
  obj.innerHTML = p[22];
  obj = a('spX'); 
  obj.innerHTML = p[0];
  obj = a('spY'); 
  obj.innerHTML = p[1];
  obj = a('spRA'); 
  obj.innerHTML = p[4];
  obj = a('spDec'); 
  obj.innerHTML = p[5];
  obj = a('spSNR'); 
  obj.innerHTML = p[6];
  obj = a('spSE'); 
  obj.innerHTML = p[7];
  obj = a('spMaxADU'); 
  obj.innerHTML = p[8];
  obj = a('sMaxSky'); 
  obj.innerHTML = p[21];
  obj = a('sFWHM'); 
  obj.innerHTML = p[9];
  obj = a('spSky'); 
  obj.innerHTML = p[10];
  obj = a('spSkyStd'); 
  obj.innerHTML = p[11];
  obj = a('txtB'); 
  obj.value = p[13];
  obj = a('txtV'); 
  obj.value = p[14];
  obj = a('txtR'); 
  obj.value = p[15];
  obj = a('txtI'); 
  obj.value = p[16];
  obj = a('txtInnerAn2'); 
  obj.selectedIndex = p[17]-1;
  obj = a('txtWidth2'); 
  obj.selectedIndex = p[18]-2;
  a('btnOK').style.color = 'gray';
  SelectType(p[12]);
  obj = a('txtColor'); 
  obj.value = p[23];
  obj = a('selCI'); 
  for(i=0;i<obj.length;i++) {
    if(obj.options[i].value == p[24]) {
      obj.selectedIndex = i;
      break;
    }
  }
  hasChenged = false;
  CancelLoading();
  if(p[2]==0) {
    a('txtName').focus();
	  a('txtName').select();
	}
};

function SelectType(startype) {
  var objTarget = a('rbtnTarget'); 
  var objMoving = a('rbtnMov'); 
  var objComp = a('rbtnComp'); 
  var objCheck = a('rbtnCheck'); 
  if(startype=='2') {
    objTarget.checked = true;
    objMoving.checked = false;
    objComp.checked = false;
    objCheck.checked = false;
    seqStat(true);
  } else if(startype=='3') {
    objTarget.checked = false;
    objMoving.checked = true;
    objComp.checked = false;
    objCheck.checked = false;
    seqStat(true);
  } else if(startype=='0') {
    objTarget.checked = false;
    objMoving.checked = false;
    objComp.checked = true;
    objCheck.checked = false;
    seqStat(false);
  } else {
    objTarget.checked = false;
    objMoving.checked = false;
    objComp.checked = false;
    objCheck.checked = true;
    seqStat(false);
  }
};

//***********************************
//******** PA / SEP *****************
//***********************************

function PA_and_Sep() {
  StartLoading();
  var prim = a('selPrim');
  var p = prim.options[prim.selectedIndex].text;
  var sec = a('selSec');
  var s = sec.options[sec.selectedIndex].text;
  PageMethods.w16(p,s,_c1,OnError);
};

function _c1(r) {
  var p = new Array();
  p = r.split('|');
  a('sPA').innerHTML = p[0];
  a('sSep').innerHTML = p[1];
  CancelLoading();
};

//***********************************
//******** PIXEL MODE FUNCTIONS *****
//***********************************

function HideMag() {
  mainMode = 0;
  ShowDiv('divLoadMag',false);
  ShowDiv('divMagTbl',false);
  ShowDiv('divAdd',false);
  ShowDiv('divMag',false);
  ShowDiv('divMenPixel',false);
  ShowDiv('divSelStar',false);
  ShowDiv('divMenu',true);
  ShowDiv('divMCat',true);
  PageMethods.w29(c12,OnError); 
};

function c13(result) {
  
  // Show pixel mode
  var r = new Array();
  r = result.split('|');
  var p = new Array();
  p = r[0].split(',');
  //magX = 1*p[0]; // keep this to use when centroid is shifted
  //magY = 1*p[1];
  var rows = 1*p[2];
  var cols = 1*p[3];
  var c = new Array();
  c = r[1].split(',');
  var cen = new Array();
  cen = r[2].split(',');
  var names = new Array();
  names = r[3].split(',');
  
  var minval = 1*a("txtLow").value;
  var maxval = 1*a("txtHigh").value;
  
  var tbl = a('tblMag');
  var tb = document.createElement('tbody');
  var cell,cellText;
  
  // Clear the table
  var len = tbl.rows.length;
  if(len) {
    for (i=len-1; i != 0; i--) 
      tbl.deleteRow(i);
  }
  if(tbl.tBodies[0]) tbl.removeChild(tbl.tBodies[0]);
  
  var index, adu, cval, bcol, fcol;
  for(i = 0; i < rows; i++) {           
    var row = document.createElement('tr');
    for(j = 0; j < cols; j++) {    
  
      index = (i*cols)+j;
      adu = c[index];      
      cval = ADUToGray(adu,255,minval,maxval,true);
      cell = document.createElement('td');
      bcol = RGB2HTML(cval);
      if(cval > 100)
        fcol = 'black';
      else
        fcol = '#888888';
      cell.style.cssText = 'text-align:center;vertical-align:middle;width:30px;height:30px;background-color:' + bcol + ';color:' + fcol + ';';
      cellText = document.createTextNode(adu);
      cell.appendChild(cellText);
      row.appendChild(cell);
      
    }
    tb.appendChild(row);
  }    
  tbl.appendChild(tb);
  
  // Draw circles
  var rad = 1*a('txtAp').value;
  var cXY = new Array();
  for(i = 0; i < cen.length; i++) {
    cXY = cen[i].split('+');
    DrawCircleAround(tbl,1*cXY[0],1*cXY[1],rad,'#aa7777');
  }
  
  // Add star names to combos
  var nstars = 0;
  var sel = a('selStarsAdjCentr');
  ClearSelect(sel);
  for(i = 0; i < names.length; i++) {
    if(names[i] != '') {
      var y=document.createElement('option');
      y.text=names[i];
      y.value=cen[i];
      try {
        sel.add(y,null); // Standard, does not work in IE
      } catch(ex) {
        sel.add(y); // IE only
      }
      nstars++;
    }
  }

  if(nstars > 0) 
    a('divSelStar').style.visibility = 'visible';
  else
    a('divSelStar').style.visibility = 'hidden';
  a("divLoadMag").style.visibility = 'hidden';
  a("divMagTbl").style.visibility = 'visible';
  
  CancelLoading();
  
};

function RefreshADUTable() {

  var minval = 1*a("txtLow").value;
  var maxval = 1*a("txtHigh").value;
  
  var tbody = a('tblMag').tBodies[0];
  var cells = tbody.getElementsByTagName('TD');
  var adu,cval,bcol,fcol;
  
  for(var i=0; i<cells.length; i++){
    // don't redraw red cells
    if(cells[i].style.backgroundColor != 'red' && cells[i].style.backgroundColor != '#aa7777') {
      adu = cells[i].innerHTML;
      cval = ADUToGray(adu,255,minval,maxval,true);
      bcol = RGB2HTML(cval);
      if(cval > 100)
        fcol = 'black';
      else
        fcol = '#888888';
      cells[i].style.cssText = 'text-align:center;vertical-align:middle;width:30px;height:30px;background-color:' + bcol + ';color:' + fcol + ';';
    }
  }
};

function SelectMagStar() {
  
  StartLoading();
  var tbl = a('tblMag');
  var s = a('selStarsAdjCentr');
  var name = s.options[s.selectedIndex].text;
  
  // Re-draw previous circle
  if(_cX!=0) {
    if(lastMagSel==name)
     DrawCircleAround(tbl,_cX,_cY,_Rad,-1);
    else
      if(name!='') DrawCircleAround(tbl,_cX,_cY,_Rad,'#aa7777');
  }
  
  lastMagSel = name;
  
  var cen = s.options[s.selectedIndex].value;
  var cXY = new Array();
  cXY = cen.split('+');
  _cX = 1*cXY[0];
  _cY = 1*cXY[1];
  _Rad = 1*a('txtAp').value;
  DrawCircleAround(tbl,_cX,_cY,_Rad,'red');
  
  PageMethods.w25(name,c25,OnError);
  
};

function c25(r) {
  p = new Array();
  p = r.split('|');
  a('sCX').innerHTML = p[0];
  a('sCY').innerHTML = p[1];
  a('txtX').value = p[0];
  a('txtY').value = p[1];
  a('sSNR_mag').innerHTML = p[2];
  a('sFWHM_mag').innerHTML = p[3];
  a('sIM_mag').innerHTML = p[4];
  CancelLoading();
};

function UpdatePixelAp(dx, dy) {
  var s = a('selStarsAdjCentr');
  var name = s.options[s.selectedIndex].text;
  var tbl = a('tblMag');
  // Re-draw previous circle
  DrawCircleAround(tbl,_cX,_cY,_Rad,-1);
  // Draw new circle
  _cX += dx;
  _cY += dy;
  _Rad = 1*a('txtAp').value;
  DrawCircleAround(tbl,_cX,_cY,_Rad,'red');
  var x = 1*a('txtX').value.replace(',','.');
  var y = 1*a('txtY').value.replace(',','.');
  a('txtX').value = x+dx;
  a('txtY').value = y+dy;
};

function ApplyManualCentroid() {
  StartLoading();
  var X = a('txtX').value;
  var Y = a('txtY').value;
  var s = a('selStarsAdjCentr');
  s.options[s.selectedIndex].value = _cX + '+' + _cY;
  var name = s.options[s.selectedIndex].text;
  PageMethods.w26(name,X,Y,c26,OnError);
};

function c26(r) {
  p = new Array();
  p = r.split('|');
  a('sSNR_mag').innerHTML = p[2];
  a('sFWHM_mag').innerHTML = p[3];
  a('sIM_mag').innerHTML = p[4];
  CancelLoading();
  alert('The centroid has been updated');
};

function DrawCircleAround(tbl,row,col,rad,color) {

  var cX, cY, d;
  
  cX = 0;
  cY = rad;
  d = 1 - rad;
  DrawCirclePoints(tbl,row,col,cX,cY,color);
  while(cY > cX) {
    if(d < 0) {
      d = d + (2*cX) + 3;
      cX++;
    } else {
      d = d + 2*(cX - cY) + 5;
      cX++;
      cY--;
    }
    DrawCirclePoints(tbl,row,col,cX,cY,color);
  }
};

function DrawCirclePoints(tbl, cX, cY, x, y, color) {
  ColorCellRed(tbl, cX+x, cY+y, color);
  ColorCellRed(tbl, cX+y, cY+x, color);
  ColorCellRed(tbl, cX+y, cY-x, color);
  ColorCellRed(tbl, cX+x, cY-y, color);
  ColorCellRed(tbl, cX-x, cY-y, color);
  ColorCellRed(tbl, cX-y, cY-x, color);
  ColorCellRed(tbl, cX-y, cY+x, color);
  ColorCellRed(tbl, cX-x, cY+y, color);
};

function ColorCellRed(tbl, col, row, color) {
  if(row >= 0 && col >= 0 && row < tbl.rows.length && col < tbl.rows[0].cells.length) {
    if(color==-1) {
      var minval = 1*a("txtLow").value;
      var maxval = 1*a("txtHigh").value;
      var cell = tbl.rows[row].cells[col];
      var adu = 1*cell.innerHTML;
      var c = ADUToGray(adu,255,minval,maxval,true);
      cell.style.backgroundColor = RGB2HTML(c);
      if(c > 100)
        cell.style.color = 'black';
      else
        cell.style.color = '#888888';
      } else {
      tbl.rows[row].cells[col].style.backgroundColor = color;
      tbl.rows[row].cells[col].style.color = 'black';
    }  
  }
};

function RGB2HTML_red(val) {
    var c = '';
    if(val<16) c = '0';
    c += val.toString(16);
    c = '#ff' + c + c;
    return c;
};

function RGB2HTML(val) {
    var c = '';
    if(val<16) c = '0';
    c += val.toString(16);
    c = '#' + c + c + c;
    return c;
};

function ADUToGray(val, maxcolor, low, high, invert) {

  var icol;
  var irange, c1, c2, arg;

	if(val==0) {
	  if(invert)
	    return 255;
	  else
	    return 0;
	}

  /* scaling parameters */
  irange = high - low;
  irange = 1.0 / irange;
  
  c1 = (maxcolor - 1.0) * irange;
  c2 = low * c1 - 0.5;

  /* non blanked */
  if(val < low) val = low;
  if(val > high) val = high;

  /* Linear */
  icol = Math.round((c1 * val - c2));

  if(icol < 1) icol = 1; /* minimum color = 1 */
  if(icol >= maxcolor) icol = maxcolor - 1;

  // Invert image?
  if(invert) icol = maxcolor - icol;

  // Set the pixels with the buffer values
  return icol;
};

//***********************************
//******** EDIT MEASUREMENTS ********
//***********************************

function UpdateMeas() {
  StartLoading();
  var obj = a('txtName'); 
  var name = obj.value;
  //obj = a('hidMapName'); 
  //var mapname = obj.value;
  obj = a('txtB'); 
  var B = obj.value;
  obj = a('txtV'); 
  var V = obj.value;
  obj = a('txtR'); 
  var R = obj.value;
  obj = a('txtI'); 
  var I = obj.value;
  obj = a('txtColor'); 
  var CI = obj.value;
  obj = a('selCI');
  var CI_Band = obj.options[obj.selectedIndex].value;
  obj = a('txtAp'); 
  var ap = obj.value;
  obj = a('txtInnerAn'); 
  var ia = obj.value;
  obj = a('txtWidth'); 
  var w = obj.value;
  obj = a('txtInnerAn2'); 
  var ia2 = obj.value;
  obj = a('txtWidth2'); 
  var w2 = obj.value;
  var objTarget = a('rbtnTarget'); 
  var objMoving = a('rbtnMov'); 
  var objComp = a('rbtnComp'); 
  var objCheck = a('rbtnCheck'); 
  var mtype;
  if(objTarget.checked) 
    mtype = 2;
  else if(objMoving.checked)
    mtype = 3;
  else if(objComp.checked)
    mtype = 0;
  else
    mtype = 1;
  
  var man = false;
  if((ia != ia2) || (w != w2)) man = true;
  
  ap = ap.replace(',','.');
  B = B.replace(',','.');
  V = V.replace(',','.');
  R = R.replace(',','.');
  I = I.replace(',','.');
  
  PageMethods.w11(selStarMapName,name,mtype,B,V,R,I,ap,ia2,w2,man,CI,CI_Band,OnUpdateComplete,OnError);
  selStarMapName = name;
  
};

function OnUpdateComplete(result) {
  var p = new Array();
  p = result.split('|');
  SeqToCookies(p);
  RefreshCanvas();
  ShowMeasDiv(false);
};

function DeleteMeas(name) {
  StartLoading();
  if(!name)
    name = a('txtName').value;
  PageMethods.w10(name,OnDeleteComplete,OnError);
};

function OnDeleteComplete(result) {
  var p = new Array();
  p = result.split('|');
  SeqToCookies(p);
  RefreshCanvas();
};

//***********************************
//******** SETTINGS *****************
//***********************************

function UpdateSettings() {
  eraseCookie('minSNR');
  eraseCookie('searchRad');
  eraseCookie('infoOnClick');
  var minSNR = a('txtMinSNR').value; 
  var searchRad = a('txtSR').value; 
  var infoOnClick = a('rClick').checked; 
  createCookie('minSNR',minSNR,100);
  createCookie('searchRad',searchRad,100);
  createCookie('infoOnClick',infoOnClick,100);
  ShowDiv('divSettings',false);
};

function UpdateApCookies(ap,ia,aw) {
  eraseCookie('ap');
  eraseCookie('ia');
  eraseCookie('aw');
  createCookie('ap',ap,100);
  createCookie('ia',ia,100);
  createCookie('aw',aw,100);
};

function UpdateAnnulus() {

  StartLoading();
  var ap = a('txtAp').value.replace(',','.');; 
  var ia = a('txtInnerAn').value; 
  var w = a('txtWidth').value; 
  UpdateApCookies(ap,ia,w);
  a('sAp').innerHTML = 'Aperture radius is ' + ap + ' pixels.';
  PageMethods.w12(ap,ia,w,c12,OnError); 
  if(mainMode == 1) UpdatePixelAp(0,0);
  
};

function c12(result) {
  var p = new Array();
  p = result.split('|');
  SeqToCookies(p);
  RefreshCanvas();
  if(selStar!='') PageMethods.w4(selStar,OnMeasComplete,OnError);
};

//***********************************
//******** CLEAR MISC ***************
//***********************************

function ClearTable() {
  var tbl = a('tblMeas');
  var len = tbl.rows.length;
  for (i=len-1; i != 0; i--) 
    tbl.deleteRow(i);
  var s = a('iSelLarge').style;
  s.top = '-100px';
  s.left = '-100px';
  s = a('iSelSmall').style;
  s.top = '-100px';
  s.left = '-100px';
  measInList = 0;
};

function ClearCombos() {
  var sel = a('selPrim');
  ClearSelect(sel);
  sel = a('selSec');
  ClearSelect(sel);
};

function RemoveAll() {
  obj = a('ddlSeq2'); 
  obj.selectedIndex = i;
  // server side removal of measurements
  StartLoading();
  eraseCookiesSIMBAD();
  PageMethods.w23(OnDeleteComplete,OnError);
};

function ClearSIMBAD() {
  HideSubMenu('divMCatSub');
  eraseCookiesSIMBAD();
  ClearTable();
  ClearCombos();
  RefreshCanvas();
};

function ClearUIDs() {
  HideSubMenu('divMCatSub');
  eraseCookiesUnidentified();
  ClearTable();
  ClearCombos();
  RefreshCanvas();
};

//***********************************
//******** LOAD SEQUENCE ************
//***********************************

function LoadGCVS() {
  StartLoading();
  HideSubMenu('divMCatSub');
  var ap = a('txtAp').value.replace(',','.');
  var ia = a('txtInnerAn').value.replace(',','.');
  var w = a('txtWidth').value.replace(',','.');
  var snr = parseInt(a('txtMinSNR').value);
  var sr = parseInt(a('txtSR').value);
  PageMethods.w6(ap,ia,w,snr,false,sr,OnImportComplete,OnError);
};

function LoadAAVSOComps() {
  StartLoading();
  HideSubMenu('divMCatSub');
  var ap = a('txtAp').value.replace(',','.');
  var ia = a('txtInnerAn').value.replace(',','.');
  var w = a('txtWidth').value.replace(',','.');
  var snr = parseInt(a('txtMinSNR').value);
  var sr = parseInt(a('txtSR').value);
  PageMethods.w7(ap,ia,w,snr,sr,OnImportComplete,OnError);
};

function LoadSequence() {
  var seqID = a('hidSeqName').value;
  if(seqID == '0') seqID = a('ddlSeq2').value;
  if (seqID != '0' && seqID != '') {
    StartLoading();
    var ap = a('txtAp').value.replace(',','.');
    var ia = a('txtInnerAn').value;
    var w = a('txtWidth').value;
    var snr = parseInt(a('txtMinSNR').value);
    var sr = parseInt(a('txtSR').value);
    PageMethods.w5(seqID,ap,ia,w,snr,sr,OnImportComplete,OnError);
  }
};

function LoadPhotFile() {
  StartLoading();
  var snr = parseInt(a('txtMinSNR').value);
  var sr = parseInt(a('txtSR').value);
  PageMethods.w30(snr,sr,OnImportComplete,OnError);
};

function OnImportComplete(result) {
  var p = new Array(); // contain all elements (info, meas1, meas2, ... etc)
  p = result.split('||');
  if(p[0]=='Err') {
    CancelLoading();
    alert(p[1]);
  } else {
    var stars = p[1].split("|");
    SeqToCookies(stars);
    var uids = p[2].split("|");
    var n_uids = AddUnidentified(uids);
    RefreshCanvas();
    a('divNoMeas').style.visibility = 'hidden';
    a('divMeasures').style.visibility = 'visible';
    CancelLoading();
    a('hidSeqName').value = a('ddlSeq2').value;
    if(n_uids>0 && !uidShowed) {
      showUIDs();
      uidShowed = true;
    }
  }
};

function SeqToCookies(stars) {
  // Create cookies for the sequence
  eraseCookies();
  ClearTable();
  ClearCombos();
  var el,j=0;
  for (var i=0; i<stars.length; i++) {
    el = stars[i].split(",");
    if(el.length > 1) {
      MeasToCookie('PHM_X', 1*el[0]);  
      MeasToCookie('PHM_Y', 1*el[1]);  
      MeasToCookie('PHM_Names', el[2]);
      MeasToCookie('PHM_Type', el[3]);
      MeasToCookie('PHM_InnerAn', el[4]);
      MeasToCookie('PHM_Width', el[5]);
      MeasToCookie('PHM_SNR', parseInt(el[6]));
      MeasToCookie('PHM_FWHM', el[7]);
      j++;
    }
  }
  if(j==0) ShowMeasTable(false);
  // Draw the sequence
  //RefreshCanvas();
};

//***********************************
//******** OTHER OBJECTS ************
//***********************************

function LoadSIMBAD() {
  StartLoading();
  HideSubMenu('divMCatSub');
  PageMethods.w8(OnSIMBADComplete,OnError);
};

function OnSIMBADComplete(result) {
  
  var p = new Array(); // one element pr star
  p = result.split('||');
  if(p[0]=='Err') {
    CancelLoading();
    alert(p[1]);
  } else {
    
    eraseCookiesSIMBAD();
    var el; // star details
    for (var i=1; i<p.length; i++) {
      if(p[i] != '') {
        el = p[i].split("|");
        MeasToCookie('SIMBAD_X', 1*(el[1].replace(',','.')));  
        MeasToCookie('SIMBAD_Y', 1*(el[2].replace(',','.')));  
        MeasToCookie('SIMBAD_Names', el[0]);
      }
    }
    // Draw the sequence
    RedrawSIMBAD_Objects();
    CancelLoading();
  }
    
};

function AddUnidentified(stars) {
  
  eraseCookiesUnidentified();
  
  var nbr = 0;
  var el; // star details
  for (var i=0; i<stars.length; i++) {
    if(stars[i] != '') {
      el = stars[i].split(",");
      MeasToCookie('UID_X', 1*(el[0].replace(',','.')));  
      MeasToCookie('UID_Y', 1*(el[1].replace(',','.')));  
      MeasToCookie('UID_Names', el[2]);
      nbr++;
    }
  }
  return nbr;
  
};

//***********************************
//******** DRAW MEASUREMENTS ********
//***********************************

function RefreshCanvas() {
  RedrawSequence();
  RedrawUID_Objects();
  RedrawSIMBAD_Objects();
  CancelLoading();
};

function RedrawSequence() {

  ClearTable();  

  // Get the arrays from the cookies
  var nTargets = 0;
	var nComps = 0;
	var nChecks = 0;
	var posX = new Array();
	var posY = new Array();
	var names = new Array();
	var starType = new Array();
	var radInnerAnn = new Array();
	var radWidth = new Array();
	var snr = new Array();
	var fwhm = new Array();
	var sX = readCookie('PHM_X');
	var sY = readCookie('PHM_Y');
	var sName = readCookie('PHM_Names');
	var sType = readCookie('PHM_Type');
	var sRadInnerAnn = readCookie('PHM_InnerAn');
	var sWidth = readCookie('PHM_Width');
	var sSNR = readCookie('PHM_SNR');
	var sFWHM = readCookie('PHM_FWHM');
	
	var aperture = a('txtAp').value;
  aperture = aperture.replace(',','.');
  	
  var canvas = a("canvas");
  canvas.innerHTML = canvasDefHTML;
  var jg = new jsGraphics("canvas");
  jg.clear();
  
  var divMap = a('divMap');
  divMap.innerHTML = mapDefHTML;
  
	if(sX != null) {
	
	  posX = sX.split(',');
	  posY = sY.split(',');
	  names = sName.split(',');
	  starType = sType.split(',');
	  radInnerAnn = sRadInnerAnn.split(',');
	  radWidth = sWidth.split(',');
	  snr = sSNR.split(',');
	  fwhm = sFWHM.split(',');
  	
	  var iX;
	  var iY;
	  iX = posX[0] * 1;
  	  	
    for (var i=0; i<posX.length; i++) {
	    iX = posX[i] * 1;
		  iY = posY[i] * 1;
	    drawMeasurement(jg,1*starType[i],iX,iY,zoom*radInnerAnn[i],zoom*radWidth[i],zoom*aperture,names[i],snr[i],fwhm[i]);
	    switch (1*starType[i]) {
	      case 0:
	        nComps++;
	        break;
	      case 4:
	        nComps++;
	        break;
	      case 1:
	        nChecks++;
	        break;
	      default:
	        nTargets++;
	        break;
	    }
	  }
	  jg.paint();
	}	
	var span = a('sNTarget');
	span.innerHTML = nTargets;
	span = a('sNComp');
	span.innerHTML = nComps;
	span = a('sNCheck');
	span.innerHTML = nChecks;
};

function drawMeasurement(jg, sType, X, Y, radInnerAnn, annWidth, aperture, name, snr, fwhm) {

  jg.setFont("verdana","12px",Font.BOLD); 
  jg.setStroke(1);
  var imname;
  
  if(sType == 2) {
    jg.setColor("Green");
    imname = '../img/mg.gif';
  } else if(sType == 0) {
    jg.setColor("#1e90ff");
    imname = '../img/mb.gif';
  } else if(sType == 1) {
    jg.setColor("#CC6633");
    imname = '../img/mo.gif';
  } else if(sType == 3) {
    jg.setColor("Black");
    imname = '../img/mo.gif';
  } else {
    jg.setColor("Gray");
    imname = '../img/mgr.gif';
  }
  
  // Add image to map
  var divThumb = a('divThumb');
  var dW = parseInt(divThumb.style.width) / (FITSw);
  var dH = parseInt(divThumb.style.height) / (FITSh);
  img = document.createElement("img");
  img.src = imname;
  img.style.cssText = 'position:absolute;left:' + dW*(X-2) + 'px;' + 'top:' + dH*(Y-2) + 'px;z-index:1;';
  var divMap = a('divMap');
  divMap.appendChild(img);
 
  aperture = Math.round(aperture);
  var radOuterAnn = radInnerAnn + annWidth;
  X = zoom*X - scaleOffsetX;
  Y = zoom*Y - scaleOffsetY;
  jg.drawEllipse(X-aperture, Y-aperture, 2*aperture, 2*aperture); 
  jg.drawEllipse(X-radInnerAnn, Y-radInnerAnn, 2*radInnerAnn, 2*radInnerAnn);
  jg.drawEllipse(X-radOuterAnn, Y-radOuterAnn, 2*radOuterAnn, 2*radOuterAnn);
  jg.drawString(name,X+10,Y+10); 
  
  // Add pop-up image
  var wX = WinCoordFromFITSCoordX(X);
  var wY = WinCoordFromFITSCoordY(Y);
  var c = a('canvas'); 
  var img = document.createElement("img");
  img.src = '../img/blank.gif';
  img.style.cssText = 'position:absolute;left:' + (X-5) + 'px;' + 'top:' + (Y-5) + 'px;cursor:pointer; z-index:1;';
  if(a('rClick').checked)
    img.onclick = function(){BlankImgAction(name);};
  else
    img.onmouseover = function(){BlankImgAction(name);};
  c.appendChild(img);
  
  // Add to table
  MeasToTable(name,1*sType,snr,fwhm);
  
};

function MeasToTable(name,type,snr,fwhm) {
  var tbl = a('tbMeas');
  var row = document.createElement("tr");
  row.setAttribute('id','row_' + name);
  //cell.setAttribute('onmouseover',"javascript:b('row_" + name + "');");
  //row.onmouseover = "javascript:b('row_" + name + "');";
  row.onmouseover = function(){
    this.style.backgroundColor = '#dedede';
  };
  row.onmouseout = function() {
    this.style.backgroundColor = '#ffffff';
  };
  
  var cell;
  var cellText;
  // type
  cell = document.createElement("td");
  cell.setAttribute('height','10px');
  cell.setAttribute('width','10px');
  //cellText = document.createTextNode(type);
  //cell.appendChild(cellText);
 switch(type) {
    case 0:
      cell.style.cssText = 'background-color:blue;';
      break;
    case 1:
      cell.style.cssText = 'background-color:orange;';
      break;
    case 2:
      cell.style.cssText = 'background-color:green;';
      break;
    case 3:
      cell.style.cssText = 'background-color:black;';
      break;  
    default:
      cell.style.cssText = 'background-color:gray;';
      break;
  }
  row.appendChild(cell);
  
  // Name
  cell = document.createElement("td");
  cell.style.cssText = 'padding-left:10px;';
  var link = document.createElement("a");
  link.setAttribute('href','#');
  link.setAttribute('innerText',name);
  link.innerHTML = name;
  link.onclick = function(){MeasDetails(name);};
  //link.onclick = function(){PlaceSelector(name);};
  cell.appendChild(link);
  row.appendChild(cell);
  // SNR
  cell = document.createElement("td");
  cellText = document.createTextNode(snr);
  cell.style.cssText = 'text-align:right;padding-right:10px;';
  cell.appendChild(cellText);
  row.appendChild(cell);
  // FWHM
  cell = document.createElement("td");
  cellText = document.createTextNode(fwhm);
  cell.style.cssText = 'text-align:right;padding-right:20px;';
  cell.appendChild(cellText);
  row.appendChild(cell);
  
  // Find
  cell = document.createElement("td");
  link = document.createElement("img");
  link.setAttribute('src','../img/FindHS.png');
  link.setAttribute('alt','Locate ' + name);
  link.style.cssText = 'cursor:pointer;';
  link.onclick = function(){PlaceSelector(name);};
  cell.appendChild(link);
  row.appendChild(cell);
  
  // Delete
  cell = document.createElement("td");
  link = document.createElement("img");
  link.setAttribute('src','../img/d.png');
  link.setAttribute('alt','Delete ' + name);
  link.style.cssText = 'cursor:pointer;';
  link.onclick = function(){DeleteMeas(name);};
  cell.appendChild(link);
  row.appendChild(cell);
  tbl.appendChild(row);
  
  measInList++;
  ResizeMeaslist();
  
  // Make sure it shows
  ShowMeasTable(true);
  
  // Add to dobule star combos
  var sP = a('selPrim');
  var sS = a('selSec');
  var y = document.createElement('option');
  y.text = name;
  var x = document.createElement('option');
  x.text = name;
  try {
    sP.add(y,null); // standards compliant; doesn't work in IE
    sS.add(x,null);
  } catch(ex) {
    sP.add(y); // IE only
    sS.add(x);
  }
};

function PlaceSelector(name) {
  StartLoading();
  selStar = name;
  PageMethods.w22(name,c22,OnError);
};

function c22(r) {
  var p = new Array();
  p = r.split('|');
  var img = a('iSelLarge').style; 
  //img.left = (WinCoordFromFITSCoordX(p[0])-10) + 'px';
  //img.top = (WinCoordFromFITSCoordY(p[1])-10) + 'px';
  img.left = (zoom*p[0]-scaleOffsetX+dragOffsetX-4) + 'px';
  img.top = (zoom*p[1]-scaleOffsetY+dragOffsetY-4) + 'px';
  selStartX = parseInt(img.left) - dragOffsetX;
	selStartY = parseInt(img.top) - dragOffsetY;
  // Position small image
  img = a('iSelSmall'); 
  var divThumb = a('divThumb');
  var dW = parseInt(divThumb.style.width) / (FITSw);
  var dH = parseInt(divThumb.style.height) / (FITSh);
  img.style.left = dW*(p[0]-2) + 'px';
  img.style.top = dH*(p[1]-2) + 'px';
  CancelLoading();
};

function b(oRow) {
    if(oRow) oRow.style.backgroundColor = oRow.originalBackgroundColor;
};

function ResizeMeaslist() {
  var style = a('divTblMeas').style;
  var max = (1*myHeight - 450);
  if(max < 50) max = 50;
  var lh = measInList * 19;
  if(lh > max) lh = max;
  style.height = lh + 'px';
};

function MeasDetails(name) {
  selStar = name;
  SaveCanvas(2);
};

//***********************************
//******** DRAW OTHER OBJECTS *******
//***********************************

function RedrawSIMBAD_Objects() {

  // Get the arrays from the cookies
	var posX = new Array();
	var posY = new Array();
	var names = new Array();
	var sX = readCookie('SIMBAD_X');
	var sY = readCookie('SIMBAD_Y');
	var sName = readCookie('SIMBAD_Names');
  	
	if(sX != null) {
	
	  posX = sX.split(',');
	  posY = sY.split(',');
	  names = sName.split(',');
  	
	  var iX, iY;
	  iX = posX[0] * 1;
  		
    var canvas = a("canvas");
	  var jg = new jsGraphics("canvas");
	  for (var i=0; i<posX.length; i++) {
	    iX = posX[i] * 1;
		  iY = posY[i] * 1;
	    drawSIMBAD_Object(jg,iX,iY,names[i]);
	  }
	  jg.paint();

	}	
};

function drawSIMBAD_Object(jg, X, Y, name) {

  jg.setFont("verdana","12px",Font.PLAIN); 
  jg.setStroke(1);
  jg.setColor("Red");
  
  X = zoom*X - scaleOffsetX;
  Y = zoom*Y - scaleOffsetY;
  jg.drawRect(X-5, Y-5, 10, 10);
  jg.drawString(name,X+10,Y+10); 
  
  // Add pop-up image
  var wX = WinCoordFromFITSCoordX(X);
  var wY = WinCoordFromFITSCoordY(Y);
  var c = a('canvas'); 
  //c.innerHTML += '<img src=\'../img/blank.gif\' style=\'position:absolute;left:' + (X-5) + 'px;' + 'top:' + (Y-5) + 'px;cursor:pointer;\' />';
  var img = document.createElement("img");
  img.src = '../img/blank.gif';
  img.style.cssText = 'position:absolute;left:' + (X-5) + 'px;' + 'top:' + (Y-5) + 'px;cursor:pointer;';
  img.onclick = function(){NavigateSIMBAD(name);};
  c.appendChild(img);
};

function RedrawUID_Objects() {

  // Get the arrays from the cookies
	var posX = new Array();
	var posY = new Array();
	var names = new Array();
	var sX = readCookie('UID_X');
	var sY = readCookie('UID_Y');
	var sName = readCookie('UID_Names');
  	
	if(sX != null) {
	
	  posX = sX.split(',');
	  posY = sY.split(',');
	  names = sName.split(',');
  	
	  var iX, iY;
	  iX = posX[0] * 1;
  		
    var canvas = a("canvas");
	  var jg = new jsGraphics("canvas");
	  for (var i=0; i<posX.length; i++) {
	    iX = posX[i] * 1;
		  iY = posY[i] * 1;
	    drawUID_Object(jg,iX,iY,names[i]);
	  }
	  jg.paint();

	}	
};

function drawUID_Object(jg, X, Y, name) {

  // Add image to map
  var divThumb = a('divThumb');
  var dW = parseInt(divThumb.style.width) / (FITSw);
  var dH = parseInt(divThumb.style.height) / (FITSh);
  img = document.createElement("img");
  img.src = '../img/circ.gif';
  img.style.cssText = 'position:absolute;left:' + dW*(X-2) + 'px;' + 'top:' + dH*(Y-2) + 'px;z-index:1;';
  var divMap = a('divMap');
  divMap.appendChild(img);

  jg.setFont("verdana","12px",Font.PLAIN); 
  jg.setStroke(1);
  jg.setColor("Red");
  
  X = zoom*X - scaleOffsetX;
  Y = zoom*Y - scaleOffsetY;
  jg.drawEllipse(X-5, Y-5, 10,10); 
  jg.drawString(name,X+10,Y+10); 
  
  // Add pop-up image
  var wX = WinCoordFromFITSCoordX(X);
  var wY = WinCoordFromFITSCoordY(Y);
  var c = a('canvas'); 
  var img = document.createElement("img");
  img.src = '../img/blank.gif';
  img.style.cssText = 'position:absolute;left:' + (X-5) + 'px;' + 'top:' + (Y-5) + 'px;cursor:pointer;';
  img.onclick = function(){NavigateSIMBAD(name);};
  c.appendChild(img);
};

function NavigateSIMBAD(name) {
  ignoreImgClick = true;
  window.open('http://simbad.u-strasbg.fr/simbad/sim-id?Ident=' + name.replace('+','%2B'), '_blank');
};

//***********************************
//******** USER INTERACTION *********
//***********************************

function nameSequence() {
  a('divOverlay').style.visibility = 'visible';
  a('divSeqName').style.visibility = 'visible';
  a('txtSeqName').focus();
};
  
function saveSequence() {
  var name = a('txtSeqName').value;
  PageMethods.w31(name,OnSaveComplete,OnError);
};

function OnSaveComplete(result) {
  a('hidSeqName').value = result;
  var opt = document.createElement("option");
  opt.text = a('txtSeqName').value;
  opt.value = result;
  a('ddlSeq2').options.add(opt);
  a('ddlSeq2').value = result;
  hideSave();
  alert('The sequence has been saved');
};

function hideSave() {
  a('divOverlay').style.visibility = 'hidden';
  a('divSeqName').style.visibility = 'hidden';
}

function SaveSeq() {
  var name = a('hidSeqName').value;
  if(name=='0')
    nameSequence();
  else
    PageMethods.w15(name,OnSaveComplete,OnError);
};

function showUIDs() {
  if (a('hidShowUIDMsg').value == 1) {
    a('divOverlay').style.visibility = 'visible';
    a('divUIDs').style.visibility = 'visible';
  }
};

function hideUIDs() {
  a('divOverlay').style.visibility = 'hidden';
  a('divUIDs').style.visibility = 'hidden';
  if (a('chkNoShow').checked == 1) PageMethods.w30();
};

//***********************************
//******** CURSOR TRACKING **********
//***********************************

function getMouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;};
function getMouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;};

// Main function to retrieve mouse x-y pos.s
function getMouseXY(e) {

  mX = getMouseX(e);
  mY = getMouseY(e);
  
  var browserName=navigator.appName.toLowerCase();
  if (browserName.indexOf("explorer") != -1) {
    mX = mX-3;
    mY = mY-3;
  }
  else {
    mX = mX-1;
    mY = mY-1;
  }
  
  imgX = mX - offsetLeft;
  imgY = mY - offsetTop;
  imgX = imgX + scaleOffsetX - dragOffsetX;
  imgY = imgY + scaleOffsetY - dragOffsetY;
  /*var browserName=navigator.appName.toLowerCase();
  if (browserName.indexOf("explorer") != -1) {
    imgX = imgX-3;
    imgY = imgY-3;
  }
  else {
    imgX = imgX-1;
    imgY = imgY-1;
  }*/
  imgX = Math.ceil(imgX/zoom);
  imgY = Math.ceil(imgY/zoom);
  if (imgX < 0 || imgY < 0) {
    imgX = 0;
    imgY = 0;
  }
};

function movePointerInfo(e) {
  
  getMouseXY(e);

  document.formImg.MouseX.value = imgX;
  document.formImg.MouseY.value = imgY;
    
  var offX = 15;
  var offY = 15;
  var info = a('posInfo').style; 
  if (imgX > 0 && imgY > 0) {
    info.visibility = 'visible';
    info.left = (mX+offX) + 'px';
    info.top = (mY+offY) + 'px';
    obj = a('showInfoXY');
    obj.innerHTML = 'X: ' + imgX + ', Y: ' + imgY;
    RADecFromXY(imgX,imgY);
  } else {
    info.visibility = 'hidden';
  }
  if(!hasChenged) {
    a('popInfo').style.visibility = 'hidden';
    a('divColor').style.visibility = 'hidden';
    a('divSeq').style.visibility = 'hidden';
  }
  
  return true;
};

/*function hidePop() {
  var obj = a("popInfo").style; 
  obj.visibility = 'hidden';
};*/

function RADecFromXY(x, y) {

  var c11 = parseFloat(document.formImg.hidC11.value);
  var c12 = parseFloat(document.formImg.hidC12.value);
  var c21 = parseFloat(document.formImg.hidC21.value);
  var c22 = parseFloat(document.formImg.hidC22.value);
  var px0 = parseFloat(document.formImg.hidPX0.value);
  var py0 = parseFloat(document.formImg.hidPY0.value);
  var ra0 = parseFloat(document.formImg.hidRA0.value);
  var dec0 = parseFloat(document.formImg.hidDec0.value);
  
  var xi = c11 * (x - px0) + c12 * (y - py0);
  var eta = c21 * (x - px0) + c22 * (y - py0);
  xi = DegToRad(xi);
  eta = DegToRad(eta);
  
  var ra0Rad = DegToRad(ra0);
  var dec0Rad = DegToRad(dec0);
  
  var ra = Math.atan2(xi, Math.cos(dec0Rad) - eta * Math.sin(dec0Rad)) + ra0Rad;
  var _a = eta * Math.cos(dec0Rad) + Math.sin(dec0Rad);
  var b = (Math.cos(dec0Rad) - eta * Math.sin(dec0Rad));
  var c = Math.sqrt(b * b + xi * xi);
  var dec = Math.atan2(_a, c);

  ra = RadToDeg(ra);
  dec = RadToDeg(dec);

  if(ra < 0) ra = ra + 360;
  
  var sRA = DegreesToText(ra,1);
  var sDecl = DegreesToText(dec,0);
  var obj = a('showInfoRA');
  obj.innerHTML = 'R.A.: ' + sRA;
  obj = a('showInfoDec');
  obj.innerHTML = 'Dec: ' + sDecl;

};

function DegToRad(val) {
  return val * Math.PI / 180;
};

function RadToDeg(val) {
  return val * 180 / Math.PI;
};

function DegreesToText(v, isRA) {
  
  var value = parseFloat(v);
  var sign = '';
  
  if(value < 0) sign = '-';
  
  if(isRA == 1) value = value / 15;
  
  var d = Math.floor(Math.abs(value));
  if(sign == '-') 
    value = Math.abs(value + d);
  else
    value = Math.abs(value - d);
  value = value*60;
  var m = Math.floor(value);
  value = value - m;
  var s = value*60;
  var sWhole = Math.floor(s);
  s = s - sWhole;
    
  return sign + leadingZero(d) + ':' + leadingZero(m) + ':' + leadingZero(sWhole);
  
};

function leadingZero(x){
   return (x>9)?x:'0'+x;
};

function PadDigits(n, totalDigits) { 
    n = n.toString(); 
    var pd = ''; 
    if (totalDigits > n.length) 
    { 
        for (i=0; i < (totalDigits-n.length); i++) 
        { 
            pd += '0'; 
        } 
    } 
    return pd;
};

function FITSCoordFromWinCoordX(WinX) {
  var fX = WinX + scaleOffsetX - offsetLeft - dragOffsetX;
  fX = Math.ceil(fX/zoom);
  return fX;
};

function FITSCoordFromWinCoordY(WinY) {
  var fY = WinY + scaleOffsetY - offsetTop - dragOffsetY;
  fY = Math.ceil(fY/zoom);
  return fY;
};

function WinCoordFromFITSCoordX(FITSX) {
  var wX = FITSX - scaleOffsetX + dragOffsetX;
  wX = Math.ceil(wX*zoom);
  return wX;
};

function WinCoordFromFITSCoordY(FITSY) {
  var wY = FITSY - scaleOffsetY + dragOffsetY;
  wY = Math.ceil(wY*zoom);
  return wY;
};


/**
*
*  Crossbrowser Drag Handler
*  http://www.webtoolkit.info/
*
**/


var DragHandler = {


	// private property.
	_oElem : null,


	// public method. Attach drag handler to an element.
	attach : function(oElem) {
		oElem.onmousedown = DragHandler._dragBegin;

		// callbacks
		oElem.dragBegin = new Function();
		oElem.drag = new Function();
		oElem.dragEnd = new Function();

		return oElem;
	},


	// private method. Begin drag process.
	_dragBegin : function(e) {
		var oElem = DragHandler._oElem = this;

		if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
		if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }

		var x = parseInt(oElem.style.left);
		var y = parseInt(oElem.style.top);

		e = e ? e : window.event;
		oElem.mouseX = e.clientX;
		oElem.mouseY = e.clientY;

		oElem.dragBegin(oElem, x, y);

		document.onmousemove = DragHandler._drag;
		document.onmouseup = DragHandler._dragEnd;
		return false;
	},


	// private method. Drag (move) element.
	_drag : function(e) {
		var oElem = DragHandler._oElem;

		var x = parseInt(oElem.style.left);
		var y = parseInt(oElem.style.top);

		e = e ? e : window.event;
		oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px';
		oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px';

		oElem.mouseX = e.clientX;
		oElem.mouseY = e.clientY;

		oElem.drag(oElem, x, y);

		return false;
	},


	// private method. Stop drag process.
	_dragEnd : function() {
		var oElem = DragHandler._oElem;

		var x = parseInt(oElem.style.left);
		var y = parseInt(oElem.style.top);

		oElem.dragEnd(oElem, x, y);

		document.onmousemove = null;
		document.onmouseup = null;
		DragHandler._oElem = null;
	}

};

/*
wz_jsgraphics.js    v. 2.33
The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de
*/
var jg_ihtm, jg_ie, jg_fast, jg_dom, jg_moz,
jg_n4 = (document.layers && typeof document.classes != "undefined");

function chkDHTM(x, i)
{
	x = document.body || null;
	jg_ie = x && typeof x.insertAdjacentHTML != "undefined";
	jg_dom = (x && !jg_ie &&
		typeof x.appendChild != "undefined" &&
		typeof document.createRange != "undefined" &&
		typeof (i = document.createRange()).setStartBefore != "undefined" &&
		typeof i.createContextualFragment != "undefined");
	jg_ihtm = !jg_ie && !jg_dom && x && typeof x.innerHTML != "undefined";
	jg_fast = jg_ie && document.all && !window.opera;
	jg_moz = jg_dom && typeof x.style.MozOpacity != "undefined";
};


function pntDoc()
{
	this.wnd.document.write(jg_fast? this.htmRpc() : this.htm);
	this.htm = '';
};


function pntCnvDom()
{
	var x = document.createRange();
	x.setStartBefore(this.cnv);
	x = x.createContextualFragment(jg_fast? this.htmRpc() : this.htm);
	this.cnv.appendChild(x);
	this.htm = '';
};


function pntCnvIe()
{
	this.cnv.insertAdjacentHTML("BeforeEnd", jg_fast? this.htmRpc() : this.htm);
	this.htm = '';
};


function pntCnvIhtm()
{
	this.cnv.innerHTML += this.htm;
	this.htm = '';
};


function pntCnv()
{
	this.htm = '';
};


function mkDiv(x, y, w, h)
{
	this.htm += '<div style="position:absolute;z-index:1;'+
		'left:' + x + 'px;'+
		'top:' + y + 'px;'+
		'width:' + w + 'px;'+
		'height:' + h + 'px;'+
		'clip:rect(0,'+w+'px,'+h+'px,0);'+
		'background-color:' + this.color +
		(!jg_moz? ';overflow:hidden' : '')+
		';"><\/div>';
};


function mkDivIe(x, y, w, h)
{
	//this.htm += '%%'+this.color+';'+x+';'+y+';'+w+';'+h+';';
	this.htm += '<div style="position:absolute;z-index:1;'+
		'left:' + x + 'px;'+
		'top:' + y + 'px;'+
		'width:' + w + 'px;'+
		'height:' + h + 'px;'+
		'clip:rect(0,'+w+'px,'+h+'px,0);'+
		'background-color:' + this.color +
		(!jg_moz? ';overflow:hidden' : '')+
		';"><\/div>';
};


function mkDivPrt(x, y, w, h)
{
	this.htm += '<div style="position:absolute;z-index:1;'+
		'border-left:' + w + 'px solid ' + this.color + ';'+
		'left:' + x + 'px;'+
		'top:' + y + 'px;'+
		'width:0px;'+
		'height:' + h + 'px;'+
		'clip:rect(0,'+w+'px,'+h+'px,0);'+
		'background-color:' + this.color +
		(!jg_moz? ';overflow:hidden' : '')+
		';"><\/div>';
}


function mkLyr(x, y, w, h)
{
	this.htm += '<layer '+
		'left="' + x + '" '+
		'top="' + y + '" '+
		'width="' + w + '" '+
		'height="' + h + '" '+
		'bgcolor="' + this.color + '"><\/layer>\n';
};


var regex =  /%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;
function htmRpc()
{
	return this.htm.replace(
		regex,
		'<div style="overflow:hidden;position:absolute;background-color:'+
		'$1;left:$2;top:$3;width:$4;height:$5"></div>\n');
};


function htmPrtRpc()
{
	return this.htm.replace(
		regex,
		'<div style="overflow:hidden;position:absolute;background-color:'+
		'$1;left:$2;top:$3;width:$4;height:$5;border-left:$4px solid $1"></div>\n');
};


function mkLin(x1, y1, x2, y2)
{
	if (x1 > x2)
	{
		var _x2 = x2;
		var _y2 = y2;
		x2 = x1;
		y2 = y1;
		x1 = _x2;
		y1 = _y2;
	}
	var dx = x2-x1, dy = Math.abs(y2-y1),
	x = x1, y = y1,
	yIncr = (y1 > y2)? -1 : 1;

	if (dx >= dy)
	{
		var pr = dy<<1,
		pru = pr - (dx<<1),
		p = pr-dx,
		ox = x;
		while ((dx--) > 0)
		{
			++x;
			if (p > 0)
			{
				this.mkDiv(ox, y, x-ox, 1);
				y += yIncr;
				p += pru;
				ox = x;
			}
			else p += pr;
		}
		this.mkDiv(ox, y, x2-ox+1, 1);
	}

	else
	{
		var pr = dx<<1,
		pru = pr - (dy<<1),
		p = pr-dy,
		oy = y;
		if (y2 <= y1)
		{
			while ((dy--) > 0)
			{
				if (p > 0)
				{
					this.mkDiv(x++, y, 1, oy-y+1);
					y += yIncr;
					p += pru;
					oy = y;
				}
				else
				{
					y += yIncr;
					p += pr;
				}
			}
			this.mkDiv(x2, y2, 1, oy-y2+1);
		}
		else
		{
			while ((dy--) > 0)
			{
				y += yIncr;
				if (p > 0)
				{
					this.mkDiv(x++, oy, 1, y-oy);
					p += pru;
					oy = y;
				}
				else p += pr;
			}
			this.mkDiv(x2, oy, 1, y2-oy+1);
		}
	}
};

function mkOv(left, top, width, height)
{
	var a = width>>1, b = height>>1,
	wod = width&1, hod = (height&1)+1,
	cx = left+a, cy = top+b,
	x = 0, y = b,
	ox = 0, oy = b,
	aa = (a*a)<<1, bb = (b*b)<<1,
	st = (aa>>1)*(1-(b<<1)) + bb,
	tt = (bb>>1) - aa*((b<<1)-1),
	w, h;
	while (y > 0)
	{
		if (st < 0)
		{
			st += bb*((x<<1)+3);
			tt += (bb<<1)*(++x);
		}
		else if (tt < 0)
		{
			st += bb*((x<<1)+3) - (aa<<1)*(y-1);
			tt += (bb<<1)*(++x) - aa*(((y--)<<1)-3);
			w = x-ox;
			h = oy-y;
			if (w&2 && h&2)
			{
				this.mkOvQds(cx, cy, -x+2, ox+wod, -oy, oy-1+hod, 1, 1);
				this.mkOvQds(cx, cy, -x+1, x-1+wod, -y-1, y+hod, 1, 1);
			}
			else this.mkOvQds(cx, cy, -x+1, ox+wod, -oy, oy-h+hod, w, h);
			ox = x;
			oy = y;
		}
		else
		{
			tt -= aa*((y<<1)-3);
			st -= (aa<<1)*(--y);
		}
	}
	this.mkDiv(cx-a, cy-oy, a-ox+1, (oy<<1)+hod);
	this.mkDiv(cx+ox+wod, cy-oy, a-ox+1, (oy<<1)+hod);
};

function mkRect(x, y, w, h)
{
	var s = this.stroke;
	this.mkDiv(x, y, w, s);
	this.mkDiv(x+w, y, s, h);
	this.mkDiv(x, y+h, w+s, s);
	this.mkDiv(x, y+s, s, h-s);
};

function jsgFont()
{
	this.PLAIN = 'font-weight:normal;';
	this.BOLD = 'font-weight:bold;';
	this.ITALIC = 'font-style:italic;';
	this.ITALIC_BOLD = this.ITALIC + this.BOLD;
	this.BOLD_ITALIC = this.ITALIC_BOLD;
};
var Font = new jsgFont();


function jsgStroke()
{
	this.DOTTED = -1;
}
var Stroke = new jsgStroke();


function jsGraphics(id, wnd)
{
	this.setColor = new Function('arg', 'this.color = arg.toLowerCase();');

	this.setStroke = function(x)
	{
		this.stroke = x;
		this.drawLine = mkLin;
		this.mkOv = mkOv;
		this.drawRect = mkRect;
	};


	this.setPrintable = function(arg)
	{
		this.printable = arg;
		if (jg_fast)
		{
			this.mkDiv = mkDiv;
			this.htmRpc = arg? htmPrtRpc : htmRpc;
		}
		else this.mkDiv = jg_n4? mkLyr : arg? mkDivPrt : mkDiv;
	};


	this.setFont = function(fam, sz, sty)
	{
		this.ftFam = fam;
		this.ftSz = sz;
		this.ftSty = sty || Font.PLAIN;
	};


	this.drawPolyline = this.drawPolyLine = function(x, y, s)
	{
		for (var i=0 ; i<x.length-1 ; i++ )
			this.drawLine(x[i], y[i], x[i+1], y[i+1]);
	};


	this.fillRect = function(x, y, w, h)
	{
		this.mkDiv(x, y, w, h);
	};


	this.drawPolygon = function(x, y)
	{
		this.drawPolyline(x, y);
		this.drawLine(x[x.length-1], y[x.length-1], x[0], y[0]);
	};


	this.drawEllipse = this.drawOval = function(x, y, w, h)
	{
		this.mkOv(x, y, w, h);
	};


	this.drawString = function(txt, x, y)
	{
		this.htm += '<div style="position:absolute;white-space:nowrap;z-index:1;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'font-family:' +  this.ftFam + ';'+
			'font-size:' + this.ftSz + ';'+
			'color:' + this.color + ';' + this.ftSty + '">'+
			txt +
			'<\/div>';
	};


/* drawStringRect() added by Rick Blommers.
Allows to specify the size of the text rectangle and to align the
text both horizontally (e.g. right) and vertically within that rectangle */
	this.drawStringRect = function(txt, x, y, width, halign)
	{
		this.htm += '<div style="position:absolute;overflow:hidden;z-index:1;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'width:'+width +'px;'+
			'text-align:'+halign+';'+
			'font-family:' +  this.ftFam + ';'+
			'font-size:' + this.ftSz + ';'+
			'color:' + this.color + ';' + this.ftSty + '">'+
			txt +
			'<\/div>';
	};


	this.drawImage = function(imgSrc, x, y, w, h, a)
	{
		this.htm += '<div style="position:absolute;'+
			'left:' + x + 'px;'+
			'top:' + y + 'px;'+
			'width:' +  w + ';'+
			'height:' + h + ';">'+
			'<img src="' + imgSrc + '" width="' + w + '" height="' + h + '"' + (a? (' '+a) : '') + '>'+
			'<\/div>';
	};


	this.clear = function()
	{
		this.htm = "";
		if (this.cnv) this.cnv.innerHTML = this.defhtm;
	};


	this.mkOvQds = function(cx, cy, xl, xr, yt, yb, w, h)
	{
		this.mkDiv(xr+cx, yt+cy, w, h);
		this.mkDiv(xr+cx, yb+cy, w, h);
		this.mkDiv(xl+cx, yb+cy, w, h);
		this.mkDiv(xl+cx, yt+cy, w, h);
	};

	this.setStroke(1);
	this.setFont('verdana,geneva,helvetica,sans-serif', String.fromCharCode(0x31, 0x32, 0x70, 0x78), Font.PLAIN);
	this.color = '#000000';
	this.htm = '';
	this.wnd = wnd || window;

	if (!(jg_ie || jg_dom || jg_ihtm)) chkDHTM();
	if (typeof id != 'string' || !id) this.paint = pntDoc;
	else
	{
		this.cnv = document.all? (this.wnd.document.all[id] || null)
			: a? (this.wnd.a(id) || null)
			: null;
		this.defhtm = (this.cnv && this.cnv.innerHTML)? this.cnv.innerHTML : '';
		this.paint = jg_dom? pntCnvDom : jg_ie? pntCnvIe : jg_ihtm? pntCnvIhtm : pntCnv;
	}

	this.setPrintable(false);
};

function integer_compare(x,y)
{
	return (x < y) ? -1 : ((x > y)*1);
};