/*++++++++++++++
.IDENTIFICATION viz2.js
.LANGUAGE       JavaScript
.AUTHOR         Francois Ochsenbein [CDS]
.ENVIRONMENT    VizieR
.VERSION  1.0   01-May-2001
.VERSION  1.1   12-May-2001: Keep lists of opened windows.
.VERSION  1.2   16-Oct-2001
.VERSION  1.3   12-Apr-2002; VOTable output
.VERSION  1.4   06-Oct-2002: Addition of LAYER (adapted from ADS)
.VERSION  1.5   20-Nov-2002: VOPlot -- PROBLEM IE which UNESCAPES the java!!
.VERSION  1.6   09-Jul-2003: envURLbase envURLhost
.VERSION  1.7   31-Mar-2004: clearFields bug
.VERSION  1.8   02-May-2007: Use a test argument in aW
.VERSION  1.9   21-Oct-2007: GoogleSky + .. (changeOutput modes)
.VERSION  2.0   30-Sep-2008: showFlag
.COMMENTS       All JavaScript Routines used by VizieR
---------------*/

/*===========================================================================
                Definitions
 *===========================================================================*/

  Xdig = new String; Xdig = "0123456789ABCDEF";
  vMozilla=new Number;
  argColors=new String;argColors="";
  orgAction=new String;orgAction="";//orgAction=form.a;
  orgMethod=new String;
  // Keep the List of Windows 
  wName=new Array();  wList = new Array();
  //alert('orgAction=' + orgAction + 'length=' + orgAction.length);
  envVOPlot=new String; envVOPlot="/viz-bin/Echo";
  envURLbase=new String; envURLbase="/viz-bin/";
  envURLhost=new String; envURLhost="";

/*===========================================================================
                Generic JavaScript utilities
 *===========================================================================*/

function ns3el(form, name) {	// For Netscape3 which has no hash array ? 
  var n = form.elements.length;
  var o = form.elements; // Netscape 3 doesn't work with form['-source']
  for (var i=0; i<n; i++) { if (o[i].name == name) return(o[i])}
  // alert('No such element: ' + name); // Apparently, doesn' work...
  return(0)
}

// Clear 1 element in form
function clearField(ob, el) { 
  var o=ob; if (el) o = ob.form[el] ;
  if (o.type == 'text' || o.type == 'hidden') { o.value = ""; return }
  if (o.type == 'checkbox') { o.checked = false ; return }
  if (o.type == 'select-multiple') { o.selectedIndex = -1 ; return }
  if (o.type == 'select-one') { o.selectedIndex = -1 ; return }
  if (o.type == 'reset') return;
  if (o.type == 'button') return;
  if (o.type == 'submit') return;
  alert("Can't clear field: " + o.name) ;
}

// Set a value in Form (hidden or text)
function setValue(ob,name,value){
  var o = ns3el(ob.form, name);
  o.value = value;
}
// Set the vMozilla value
function setMozilla(v) {
  // alert("setMozilla(" + v + ")");
  vMozilla = v
}

// Verify at least one button of a series is pushed
function checkPushed(ob, name) {
  var form = ob.form; var n = form.elements.length; var i = 0 ;
  var o = form.elements; // Netscape 3 doesn't work with form['-source']
  for (var i=0; i<n; i++) {
    if (o[i].name != name) continue;
    if ((o[i].type != 'checkbox') && (o[i].type != 'radio')) continue;
    if (o[i].checked) return(true);
  }
  return(false);
}

// Choose the radio button to set
function setRadio(form, name, value) {
  var n = form.elements.length;  var o = form.elements;  var r = 0;
  for (var i=0; i<n; i++) {
    if (o[i].name == name) { 
      o[i].checked = (o[i].value == value);       
      r += o[i].checked;
    }
  }
  //if (r != 1) alert('Sum of ' + name + ' radio buttons = ' + r);
  return(0)
}

// Set the element in a list
function setOption(o, value) {
  var n = o.options.length;
  var i = 0;
  for (i=0; i<n; i++) {
    if (o.options[i].text.indexOf(value) >= 0) { o.selectedIndex=i; break; }
  }
  if (i>=n) alert('Could not setOption(' + name + ') to ' + value)
  return(0)
}

// Clear elements of form which name starts by a text
// Name equates text when arguments ends with a =
// Special case, if name_start is "*", all non-ASU fields are cleared
function clearFields(ob, name_start) {
  var form = ob.form; if (!form) form = ob;
  var n = form.elements.length; var i ; var text; 
  var cmp = "";		// In case of comparison
  i= name_start.indexOf("=");
  if (i>0) cmp = name_start.substr(0, i);
  for (i = 0 ; i < form.length; i++) {
    text = form.elements[i].name ;
    if (name_start == "*") {
      if ((text.charAt(0) != "-") && (form.elements[i].type == "text"))
	   { clearField(form.elements[i]) }
    } 
    else if (cmp != "") {
	if (cmp == text) clearField(form.elements[i]);
    }
    else {
      if (text.indexOf(name_start) == 0) { clearField(form.elements[i]) }
    }
  }
}

/*===========================================================================
                Popup windows: Help, References, Notes ...
			Window name = aName[_[width_x]height]
 *===========================================================================*/

function full_escape(text) {		// + sometimes NOT converted ???
  var i, tmp;
  tmp = escape(text);
  while (tmp.indexOf('+') >= 0) {
     i = tmp.indexOf('+');
     tmp = tmp.substr(0,i) + "%2b" + tmp.substr(i+1);
  }
  return(tmp);
}

function aW(name,url) {		// Generic Popup Window name_XxY_attr
  var fullURL;
  var n = wName.length ; var wn = name ;
  var tmp, w, i, x, y ;
  var a = 'scrollbars,resizable,toolbar=0,location=0,status=0,menubar=0';
  /* Must compute the fully Qualified URL */
  if (url.indexOf('://') >= 0) { fullURL = url }	// Already complete
  else { if (url.substr(0,1) == '/') { fullURL = envURLhost + url }
  else { fullURL = envURLbase + url }}
  i = fullURL.indexOf('//*&'); 
  if (i>0) {	// Already translated
    // alert("fullURL=" + fullURL);
    tmp = fullURL.substr(i);
    fullURL = fullURL.substr(0,i);
    while (tmp.indexOf('&')>0) {
      i = tmp.indexOf('&');
      fullURL = fullURL + full_escape(tmp.substr(0,i)) + '&';
      tmp = tmp.substr(i+1);
    }
    fullURL = fullURL + full_escape(tmp);
  }
  x = 640; y = 320;			// Default dimensions
  i = name.indexOf('_'); 
  if (i >= 0) { 		// e.g. MyWindow_500x500
      wn = name.substr(0, i);
      tmp = name.substr(i+1);
      i = tmp.indexOf('_') ;	// Maybe attributes ? 
      if (i>=0) { a = tmp.substr(i+1); tmp = tmp.substr(0, i) }
      i = tmp.indexOf('x') ;
      if (i >= 0) { x =  Number(tmp.substr(0, i)); y = Number(tmp.substr(i+1)) }
      else { y = Number(tmp) }
  }
  if (wn == "") { wn = "W" + wName.length; i = n }
  else for (i=0; i<n; i++) { 
      if (wName[i] != wn) continue ;
      w = wList[i]; 
      if (w.closed) w = 0; 
      break ;
  }
  // alert("aw(" + name + ")\ny=" + y + "\nwn=" + wn);
  if (w) {	// Window already exists !
    // alert("Window exists from wn=" + wn + "\nname=" + w.name);
    //*Can't change in Firebird! if ((y > 100) && (y <= 640)) w.innerHeight = y;
    //*Can't change in Firebird! if ((x > 100) && (x <= 640)) w.innerWidth  = x;
    w = window.open(fullURL, wn) ;
  }
  else { 	// New window -- create it 
    tmp= a + ',height=' + y + ',width=' + x ;
    // alert("open " + wn + ": " + tmp) ;
    w = window.open(fullURL, wn, tmp) ;
    wName[i] = wn; wList[i] = w ;
  }
  w.focus();
}

function vHelp(q) {
  var w = aW('wHelp', 'vizHelp?'+argColors+q) ;
}


function vRef(q) {	// Problem IE which unescapes!!!
  var w = aW('wRefs', '/viz-bin/VizieR?-6N&-out.form=H0&'+argColors+q);
}

function Note(catid,notid) {
  var w = aW('wNote', 'VizieR-n?-source=METAnot&catid='+catid+'&notid='+notid
    +'&-out=text') ;
}

function Unit(u) {
  var w = aW('wUnit', '/viz-bin/Unit/w?-n&'+full_escape(u)) ;
}

function UCD(u) {
  var w = aW('wUCD', 'VizieR-n?-source=METAfam&famid='+u) ;
}

function UCD1p(u) {
  var deco = "-6n&-out.form=H0+N&-source=METAucd&-out=name,explain&";
  var cond = "ucdid=" + (u&1023); u >>= 10; u &= 0x3fffff;
  while (u!=0) { cond = cond + "," + (u&1023); u >>= 10; }
  var w = aW("wUCD", "VizieR?" + deco + cond) ;
}

function vNote(q) {
  //alert('VizieR?-6N&-out.form=H0&'+argColors+q);
  var w = aW('wNote', 'VizieR?-6N&-out.form=H0&'+argColors+q) ;
}

// From a table + value, give the components making up the flags.
// If 10 values or more: edit only non-zero flags
function edX2(n) {	// Edit number 2<<n
  var res = ""; var v = n;
  for (v=n; v >= 4; v -= 4) res = res + "0";
  res =  Xdig.charAt(1<<v) + res;
  return(res);
}
function edX(n) {	// Hexadecimal edition
  if (n==0) return("0");
  var res = ""; 
  for (var v=n; v!=0; v=v>>>4) res = Xdig.charAt(v&0xf) + res;
  return(res);
}
function showFlag(tab, value) {
  //if (value == 0) return;
  var s = typeof(value) == 'string' ? true : false ;
  var x = tab.length>=8 ? true : false;	// Defaut hexa edition
  var a = x; // Edit all values
  if (tab.edit) { x = tab.edit.indexOf("x")>=0; a = tab.edit.indexOf("0")>=0; }
  var n = tab.name ? tab.name : "" ;
  var t = tab.title ? tab.title : "Meaning of " + n + " flags" ;
  var o = tab.options ? tab.options : 
      "width=640,height=320,toolbar=no,scrollbars=yes,resizable=yes";
  var w = open("", n == "" ? "_blank" : n, o);
  w.document.write("<TITLE>" + t + "</TITLE>");
  w.document.write("<BODY bgcolor='#ededff'>\n");
  w.document.write("" + n + " Flag <font color='blue'>");
  if (s)      w.document.write("0x<b>" + value + "</b></font>");
  else if (x) w.document.write("0x<b>" + edX(value) + "</b></font> (" 
              + value + ")");
  else        w.document.write("<b>" + value + "</b></font>");
  w.document.write(" means:\n");
  w.document.write("<TABLE border=1 bgcolor='white' CELLPADDING=5>");
  var v, i,m, bg, fg, text;
  v = s ? value.length : value;
  for (i=0; (i<tab.length)||(v!=0); i++) {
    var tr = false;
    m = 1<<i; bg="";
    text = tab[i] ? tab[i] : "Unexplained flag??";
    if (s) { // get hexadigit
      v = value.length-1-(i>>2);
      if (i>=0) v = (Xdig.indexOf(value.charAt(v))) >> (i&3);
      else v = 0;
    }
    if ((v&1)!=0) {
      tr = true;
      bg = tab[i] ? "" : "bgcolor='#ffe0e0'" ;
      fg = tab[i] ? "" : "<font color='red'>";
      w.document.write("<tr " + bg + "><td align='right'>");
      if (a)   w.document.write("<font color='blue'>");
      if (x|s) w.document.write("0x<b>" + edX2(i) + "</b>");
      else     w.document.write("<b>" + m  + "</b>")
      if (a)   w.document.write("</font>");
    }
    else if (!a) ;
    else if (tab[i]) {
      tr = true;
      bg = "bgcolor='#ededff'" ;
      fg = "<font color='#b0b0b0'>";
      w.document.write("<tr " + bg + "><td align='right'>");
      if (x|s) w.document.write("0x" + edX2(i));
      else     w.document.write("" + m);
    }
    if (tr) {
      w.document.write("</td><td>" + fg + text);
      if (fg != "") w.document.write("</font>");
      w.document.write("</td></tr>\n");
    }
    v = v>>>1;
  }
  w.document.write("</TABLE></BODY>");
  w.document.close();
  w.focus();
}

/*===========================================================================
   VizieR to portal
  
   note: create a form v2pform when cdsportal is choosen.
         functions changes the submit action.

         For other choices, the form (if it exists) is deleted.
  ===========================================================================*/
var v2pform=null;
var v2porigform=null;

function v2p_reset(form){
    if( !document.getElementById ) return ;

    if( v2pform!=null ){
        v2pform.parentNode.removeChild(v2pform);
        v2pform=null;

        var l=document.getElementsByTagName("input");
        for(i=0;i<l.length; i++){
            if( l[i].type=="submit") {
                if( l[i].className ) {
                    // get action from class attribute
                    var action=l[i].className.match(/\/\*.*\*\//);
                    if( action ) {
                        if( action[0] ) action=action[0]; // match return array for firefox, string for IE
                        action=action.replace(/\(.*\)/,"");
                        l[i].onclick=setViz;
                        l[i].className=l[i].className.replace(/\/\*.*\*\//,"");
                    }
                }
                else l[i].onclick=null;
            }
        }
        return ;
    }
}

function v2p_currentGETURL(){
    var url=new Array;
    if( !document.getElementById ) return "";

    var l=document.getElementsByTagName("input");
    var i;
    url[0]="";url[1]="";

    for(i=0;i<l.length;i++){
        if (!l[i].value || !l[i].name)  continue;
	if (l[i].value=="") continue;

	if (l[i].type=='hidden') {
            if( l[i].name!="+CDSportal" ) {
      	        if (url[0]!="") {url[0]=url[0]+"&";url[1]=url[1]+"&";}
                url[0]=url[0]+l[i].name+"="+encodeURIComponent(l[i].value);
                if(l[i].name=='-to') url[1]=url[1]+l[i].name+"=3";
                else url[1]=url[1]+l[i].name+"="+encodeURIComponent(l[i].value);
            }
        }

	else if (l[i].type=='text') {
	    if (url[0]!="") {url[0]=url[0]+"&";url[1]=url[1]+"&";}
            url[0]=url[0]+l[i].name+"="+encodeURIComponent(l[i].value);
            url[1]=url[1]+l[i].name+"="+encodeURIComponent(l[i].value);
        }

	else if (l[i].type=='checkbox' || l[i].type=='radio') {
	    if (l[i].checked==true) {
	        if (url[0]!="") {url[0]=url[0]+"&";url[1]=url[1]+"&";}
                url[0]=url[0]+l[i].name+"="+encodeURIComponent(l[i].value);
                url[1]=url[1]+l[i].name+"="+encodeURIComponent(l[i].value);
	    }
	}
    }

    /* get in select */
    l=document.getElementsByTagName("select");
    for(i=0;i<l.length;i++){
        if (l[i].name!='-out.form'){
	    	if (url[0]!="") {url[0]=url[0]+"&";url[1]=url[1]+"&";}
                url[0]=url[0]+l[i].name+"="+encodeURIComponent(l[i].value);
                url[1]=url[1]+l[i].name+"="+encodeURIComponent(l[i].value);
        }
    }

    var crturl=window.location+"";
    crturl=crturl.replace(/\?.*/,"");
    url[0]=crturl+"?"+url[0];
    url[1]=crturl+"?"+url[1];
    return url;
}

function v2p_create_hidden(form,name,value){
    var elt= document.createElement("input");
    elt.type="hidden";
    //elt.type="text";
    elt.name=name;
    elt.value=value;
    form.appendChild(elt);
}

function v2p_init(form){
    if( !document.getElementById ) { 
        alert("not available with current browser"); return ; }

    // create new form
    v2porigform=form;
    v2pform=document.createElement("form");
    if( document.getElementById("CDScore") )
        document.getElementById("CDScore").appendChild(v2pform);

    // change the action buttons
    var l=document.getElementsByTagName("input");
    var i;
    for(i=0;i<l.length; i++){
        if( l[i].type=="submit") {
            if( l[i].getAttribute("onClick") )  {
                // save action in class attribute
                if( l[i].className ) l[i].className="/*"+l[i].getAttribute("onClick")+"*/ "+l[i].className; 
                else l[i].className="/*"+l[i].getAttribute("onClick")+"*/";
            }
            l[i].onclick=v2p_GO;
        }
    }
}

function v2p_GO(){ 
    if( !document.getElementById ) return false;

    // not runing with list
    var l=document.getElementsByName("-file");
    for (var i=0;i<l.length;i++)
    	if (l[i].value!="" && l[i].value!="."){
    	alert("list is not running with CDSportal: "+l[i].value);
        return false;
    }

    var form=v2porigform;
    var o=ns3el(form, "+CDSportal"); 
    if( !o ) return ;

    v2pform.action=o.value ;
    v2pform.method='get';

    // destroy if exist 
    var elt=ns3el(v2pform,'destURL');
    if( elt!=0 ) elt.parentNode.removeChild(elt);
    elt=ns3el(v2pform,'requestURL');
    if( elt!=0 ) elt.parentNode.removeChild(elt);
    elt=ns3el(v2pform,'catalogue');
    if( elt!=0 ) elt.parentNode.removeChild(elt);
    elt=ns3el(v2pform,'target');
    if( elt!=0 ) elt.parentNode.removeChild(elt);

    var value="";
    var url = v2p_currentGETURL();
    
    // get catalogue
    var l=document.getElementsByName("-source");
    var i,max;
    if( l.length<10 ) max=l.length
    for(i=0;i<max;i++){
        if( l[i].value.length<100 )
            value=value+" "+l[i].value; 
    }
    value=value.replace(/^ */,"");
    v2p_create_hidden(v2pform,"catalogue", value);
 
    // get target
    value=""
    l=document.getElementsByName("-c");
    if( l.length<10 ) max=l.length
    for(i=0;i<max;i++){
        if( l[i].value.length<100 )
            value=value+" "+l[i].value; 
    }
    value=value.replace(/^ */,"");
    v2p_create_hidden(v2pform,"target", value);

    // get url into votable
    value=url[0].replace(/VizieR.*\?/,"votable?");
    //v2p_create_hidden(v2pform,"requestURL", encodeURI(value));
    v2p_create_hidden(v2pform,"requestURL", value);

    // get origin/destination
    //v2p_create_hidden(v2pform,"destURL", encodeURI(url[1]));
    v2p_create_hidden(v2pform,"destURL", url[1]);

    //return false;
    v2pform.submit(); return false ; 
}

// init and GO
function v2p_link() {
    if (!document.getElementById) return false;

    // get VizieR form
    var lform=document.getElementsByTagName("form");
    if (!lform) return false;

    for (var i=0;i<lform.length;i++) {
        if (lform[i].action) {
            if (lform[i].action.search(/VizieR/)>0) {
                v2p_init(lform[i]);
                v2p_GO();
            }
        }
    }
}

/*===========================================================================
                Change the Action to execute
 *===========================================================================*/

// Change action to what's defined by orgAction, and EXECUTE
function setViz() { 
  var form = window.document.forms[0]; 
  if (orgAction.length>0) { form.action = orgAction; form.method = orgMethod; }
  form.submit() ;
}


// Change the Action from what's selected in o = Select Option
function changeOutput(o) {
  if ((o.type != "select-one") && (o.type != "radio")) return ;
  //if (!o.type) o = o[0]; 
  var form = o.form;
  var option_selected = o.options[o.selectedIndex].text ; 
  var a = "";
  // Save the Original Action
  if (orgAction.length == 0) { 
      //alert("Set orgAction=" + a); 
      orgAction = form.action;
      orgMethod = "post";	// That's the default in all cases
  }
  var i = orgAction.lastIndexOf('/'); a = orgAction.substring(0,i+1);

  v2p_reset(form);

  if (option_selected.indexOf('XML') >= 0) {
    setRadio(form, '-oc.form', 'dec'); 		// Added 2007-10-21
    if (option_selected.indexOf('VOTable') >= 0) {
      a = a + 'votable' ;
      if (option_selected.indexOf('DTD') >= 0) a = a + '/-dtd'; 
      if (option_selected.indexOf('bin') >= 0) a = a + '/-b64'; 
      form.action = a ;
    }
    else {
      if (option_selected.indexOf('XML + CSV') >= 0) {
        form.action = a + 'votable/-tsv';
      }
      else form.action = a + 'votable/-csv' ;	// a + 'asu_xml';
    }
  }
  else if(option_selected.indexOf('VOTable') >= 0) {
    setRadio(form, '-oc.form', 'dec'); 		// Added 2007-10-21
    a = a + 'votable' ;
    if (option_selected.indexOf('bin') >= 0) a = a + '/-b64';
    //if (option_selected.indexOf('CSV') >= 0) a = a + '/-tsv';
    form.action = a ;
  }

  else if (option_selected.indexOf('SkyC') >= 0) { 
    form.action = a + 'asu-acl';      
    setRadio(form, '-oc.form', 'dec');  
  }
  else if (option_selected.indexOf('VOPlot') >= 0) {
    form.action = envVOPlot;
    form.method = "get";
    setRadio(form, '-oc.form', 'dec');  
  }
  else if (option_selected.indexOf('FIT') >= 0) {
    setRadio(form, '-oc.form', 'dec'); 		// Added 2007-10-21
    form.action = a + 'asu-fits';
  }
  else if (option_selected.indexOf('-Separated-') >= 0) {
    setRadio(form, '-oc.form', 'dec'); 		// Added 2007-10-21
    form.action = a + 'asu-tsv'; 
  }

  // Google sky
  else if ( option_selected.indexOf('KMZ') >=0 ) {
    if (ns3el(form, "-oc.form") == 0) // Mod. 2007-10-21
        alert("GoogleSky needs coordinates!");
    else {
        form.action ='kmz4GoogleSky';
        setRadio(form, '-oc.form', 'dec');
    }
  }

  // text/plain
  else if ( option_selected.indexOf('text/plain') >=0 ) {
    form.action = a + 'asu-txt';
  }

  // CDS portal
  else if ( option_selected.indexOf('CDS portal') >=0 ) {
    v2p_init(form);
    //alert("temporary disabled");
  }

  else if (option_selected.indexOf('Echo') >= 0) form.action = a + 'Echo'; 
  else if (form.action.indexOf('VizieR') < 0)  form.action = a + 'VizieR'; 
  else if (orgAction.length>0) {
      form.action = orgAction;
      form.method = orgMethod;
  }
}

// Execute one of the options of the menu
function execOutput(obj, value) {
  var form = obj.form;
  var o = ns3el(form, "-out.form") ;
  setOption(o, value);	// Choose the element in menu
  changeOutput(o);	// Change the action, method
  form.submit();
}

// Change to a GET method (for bookmarking), and EXECUTE
function changeMode() { var form = window.document.forms[0]; 
  // Verify the file is not filled 
  var f = ns3el(form,'-file') ; var c = ns3el(form,'-c') ;
  if (f && c) { 
      if (f.value == '-c' && c.value != "") {
	  alert("No file name can be bookmarked, sorry...") ;
	  return
      }
  }
  text = 'Method: ' + form.method ; 
  form.method = 'get'; // form.encoding = ''; // Problems with IE!!!
  // Be sure we've the original action...
  if (orgAction.length>0) form.action = orgAction;
  var o = ns3el(form,'-this') ; var d = ns3el(form,'-to'); 
  if (o && d) d.value = o.value; d.value += 'b';
  //alert(text + ' ---> ' + form.method); 
  //noText(form);
  form.submit() ;
}

// Submit Only when at least One Box is Checked
function execIfChecked(ob, name, msg){
  var form = ob.form;
  if (checkPushed(ob, name)) form.submit() ;
  else alert(msg);
}

// Submit from a CheckBox, and set the 'to' argument
function execCheck1(ob, phase){
  if (phase>0) setValue(ob, '-to', phase);
  ob.form.submit();
}

// Check the box of the Table/Catalog Button, and Execute
function execSource(ob,ph) { 
  var form = ob.form;
  var val = ob.value; var i=val.indexOf(' '); if(i>0) val=val.substr(0,i);
  var n = form.elements.length; var c = 0 ;
  var allCats = (val.indexOf('search ') >= 0) && (val.indexOf(' catalog') >= 0);
  if (allCats) {
      c = 1;		// This will empty the names of all catalogues.
      ph = "4c";	// This will force searching all catalogues
  }
  var o = form.elements; // Netscape 3 doesn't work with form['-source']
  for (i=0; i<n; i++) { 
    if (o[i].name == '-out') {		// Remove -out (always) if allCats asked
	o[i].checked = false;
	continue;
	//if (!allCats) continue ;
    }
    else if (o[i].name != '-source') continue;
    if (o[i].type == 'checkbox') {o[i].checked = (o[i].value == val); c++}
    else if (o[i].type == 'text' || o[i].type == 'hidden') {
	if (c==0) o[i].value = val; else o[i].value = '';c++;
    }
  }
  if (ph) { 	// Has to execute a specific Phase, e.g. '3' '4'
    o = ns3el(form,'-to'); 
    if (o) { 
      val=ph; 
      if(o.value.length > 1) val = val + o.value.substr(1); o.value = val;
    }
  }
  form.submit() ;
}

/*===========================================================================
                Special Javascript Actions
 *===========================================================================*/

// Check or Reset the 'ALL' boxes 
function allBoxes(all_box, boxes) { 
  var form = all_box.form ;
  var n = form.elements.length; var o = form.elements ;
  var nom = all_box.name ; var i;
  var stat = all_box.checked ;
  var c = form ; if (all_box.name) c = form[all_box.name]; 
  //var text = 'all_box ' + nom + ': ' + n + ' elements.\n'; 
  for (i=0; i<n; i++) { 
    if (o[i].type == 'checkbox' && o[i].name == nom) {
      o[i].checked = stat? stat : o[i].defaultChecked; 
      //text = text + '\n' + o[i].name + '=' + o[i].value       + ': ' 
      //     + o[i].checked
    }
  }
  if (boxes) {
    nom = boxes ; 
    for (i=0; i<n; i++) {
      if (o[i].type == 'checkbox' && o[i].name == nom){
	o[i].checked = stat? stat : o[i].defaultChecked; 
        //text = text + '\n' + o[i].name + '=' + o[i].value         + ': ' 
	//     + o[i].checked
      }
    }
  }
  //alert(text);
}

function unselectBox(all_box,boxe) {
   var form=all_box.form;
   var n = form.elements.length; var o = form.elements ;
   var i;
   //alert("unselect...."+n);
   for (i=0; i<n; i++) {
     if (o[i].type == 'checkbox' && o[i].name == boxe) {
       o[i].checked = '';
       allClicks=0;
     }
   }
}

// The Form Adaptation
function execAdapt(name, val, msg) { 
  if (msg) { alert(msg); return }
  var form = window.document.forms[0] ;
  var field=ns3el(form, name); var a = form.action ;
  var i = a.lastIndexOf('/'); a = a.substring(0,i+1);
  form.action = a + 'VizieR'; // Only HTML presentation of AdaptForm!
  field.name = '!-3;' + field.name + '=' + val + ';//'; 
  if ((name == '-file') && (val != '.')) form.action = form.action + '#aLIST';
  form.submit();
}

/*===========================================================================
                LAYER additions
 *===========================================================================*/

//var vers = navigator.appVersion;
var nver = navigator.appVersion.substring(0,4);
var isNS = (navigator.appName.indexOf("Netscape") !=-1);
var x,y;
var laycolor = "#ffffe0";	// Default = LightYellow
// Change the layer color
function set_laycolor(color) { laycolor = color }
// Addition of text in a layer
function lay(text){
  var t = "<table border='1' cellpadding='3' cellspacing='0' bgcolor='" + 
       laycolor + "'>" + "<tr><td>";
  t = t + text.replace(/&apos;/g, "'");
  t = t + "</td></tr></table>";
  if ((isNS) && (nver<5)) {
    df = document.xplain;
    df.document.write(t);
    df.document.close();
    df.left=x-50;
    df.top =y+10; //document.xplain.top=y+10;
  } else {
    df = document.getElementById('xplain');
    df.innerHTML=t;
    df.style.background=laycolor; // "rgb(255,255,224)"
    df.style.left=x-50;
    df.style.top=y+10;
  }
}
function laz(){	// Out of layer
  if ((isNS) && (nver<5)) { document.xplain.top=-50; }
  else {
    df = document.getElementById('xplain');
    df.innerHTML="";
  }
}
function handlerMM(e){
  x = (isNS) ? e.pageX : event.clientX + document.body.scrollLeft;
  y = (isNS) ? e.pageY : event.clientY + document.body.scrollTop;
}
if (isNS&&(nver<5)){ document.captureEvents(Event.MOUSEMOVE); }
// Install the event handler
document.onmousemove = handlerMM;
if((isNS)&&(nver<5)) {
document.write("<LAYER name=\"xplain\" visibility=\"show\" left=\"25\" top=\"-50\" z-index=\"99\"><br></LAYER>") ;
} else {
document.write("<DIV ID=\"xplain\" style=\"position:absolute; visibility:show; left:25px; top:-50px; z-index:2\"><br></DIV>") ;
}

// execute a media:  (see vizier.def for definitions)
// (latex tag in database)  =>  (html code)
// \vExec,vFile,vGraph      =>  <input type='hidden' value='command_to execute' name='\\media_type_catid'>
// \vAlert                  =>  <input type='hidden' value='text' name='\\media_alert_catid'>
// \catContent (or \vizContent in database) => <a href='execmedia()'>
// Others latex flag:
// \mediatype : type of media
// \vizcat    : the VizieR catalog name (set by vizier pgm)
// \useMedia  : 
//
// Howto:
// \catContent print the tag (associated to a catalog) with a javascript code.
// The js code display an alert if \vAlert exist for the given catalog
// Else if \vExec,vFile or Vgrap exists the given code is executed
// Else open in a new window the result catalog with option -out=*Mime(...)
//
// Note: by default the \catContent tag exute all code given by \vExec,vGraph or vFile.
//       You can limit this action with tag \useMedia(type)
//
//       Ex: \useMedia(filter)\vExec{....}
//       If you use \useMedia, all next tags (\vExec,vGraph and vFile) will not be executed
//
// Note: if there are more than one media for a given catalog (ex:2262),
//       you have to use \useMedia !
function execmedia(media,id) {
  if (!document.getElementById) return ;
  var e=document.getElementsByName("//media_alert_"+id);
  if (e && e.length>0) { alert(e[0].value); return; }
  e=document.getElementsByName("//media_"+media+"_"+id);
  if (e && e.length>0) {
    if (e.length>1) {
      var i,str,max;
      max=e.length;
      if (max>10) {
        max=10;
        alert("(trunc to ) "+max+ " tab(s) will be opened by the media "+media+" (catalog "+id+")");
      }
      else alert(max+ " tab(s) will be opened by the media "+media+" (catalog "+id+")");
      for (i=0;i<max;i++) window.open(e[i].value);
      return ; 
    }
    else window.open(e[0].value) ;
    return;
  }
  window.open("VizieR-4?-out=*&-out=*Mime("+media+")&-smedia="+id);
}
