// launch applet vars
var tappletwin = "";

// Second to wait for applets to start before we complain about it.
var appletwait = 30;

var newalertstate = new Array();
var state_unknown = -1;
var state_good = 0;
var state_warn = 1;
var state_alert = 2;

// Because some of the main stream browsers leak like hell, try to
// clean up for them before unloading page
var clearElementProps = [
 'data',
 'onmouseover',
 'onmouseout',
 'onmousedown',
 'onmouseup',
 'ondblclick',
 'onclick',
 'onselectstart',
 'oncontextmenu',
 'ncvalue',
 'connections',
 'dependencies',
 'num_total',
 'num_checked',
 'active_dependencies',
 'active_connections',
 'update_state'
];

if (window.attachEvent) {
 // attachEvent is IE 5+ only.
 window.attachEvent("onunload", function() {
  var el;
  for(var d = document.all.length;d--;){
   el = document.all[d];
   for(var c = clearElementProps.length;c--;){
    el[clearElementProps[c]] = null;
   }
  }
 });
} else {
 window.onunload = function() {
  // Seems that we cannot clean up firefox?
  return;
  var el;
  var c;
  // Traverse the entire tree and release any event handlers etc.
  // Firefox support for document.all is not sufficient
  var stack = Array();
  stack.push(window.document);
  var num_released = 0;
  try {	
   while (stack.length) {
    // pop last element
    el = stack.pop();
    if (el.nodeName == "#text")
     continue;
    // clear props
    for( c = clearElementProps.length;c--;){
     if (el.nodeName == "HTML" && (c == 8 || c == 6 || c == 5 || c == 4 || c == 3 || c == 2 || c == 1))
      continue;
     el[clearElementProps[c]] = null;
    }
    // push children
    var child = el.firstChild;
    while (child) {
     // push the child on the stack
     stack.push(child);
     child = child.nextSibling;
    }
    num_released++;
   }
  } catch (err) {
   // alert("caught error " + err.description + " element : " +
   // el.nodeName + ", " + el.id + " " + c);
  }
 };
}

// The persistent applet window reference
var pappletwin = "";

// Internal applet status. use is_papplet/lapplet_running() instead.
self.applet_is_running = 0;

// In order to make the parent and child windows able to communicate
// after browerser refreshes we continually tests the links.  If we're
// the persistent applet we poll the parent for if it has its
// pappletwin var set. If we're
setTimeout("update_parent_child_links(0)", 100);

function update_parent_child_links(num)
{
 // top.document.getElementById("dbg").innerHTML = "got op : " + self.opener + " pap " + pappletwin + " " + num + " " + document.statelist.toEvalString() + " i am " + (get_persistent_win() == self ? "child" : "parent");
 // only child windows poll
 if (self.opener != null) {
  // we're the child window
  if (top.opener.pappletwin == "") {
   top.opener.pappletwin = self;
  }
  setTimeout("update_parent_child_links(" + (num+1) + ")", 100);
 } else {
  // we're the main window
 }
}

function close_child_window()
{
 if (self.opener != null) {
  top.opener.pappletwin = "";
 }
}

// Only use the persisten window from persistent window itself or from
// javascript that is activated by the user from the main window. This
// is because the connection between the main and the persistent
// window has to be established before we can use the persistent
// window.
function get_persistent_win()
{
 if (self.opener != null) {
  return self;
 } else {
  if (typeof(pappletwin.document) != 'unknown') {
   return pappletwin.document ? pappletwin : null;
  } else
   return null;
 }
}

// Like get_persistent_win function but the other way around ie. you
// may only use this function in eigther the main window or by user
// action in persistent window.
function get_main_win()
{
 if (self.opener != null) {
  return self.opener;
 } else {
  return self;
 }
}

function set_state_list(l)
{
 var persistent = get_persistent_win();
 if (persistent) {
  var state = persistent.document.getElementById("state");
  if (state)
   state.innerHTML = l.toEvalString();
 }
}

function reset_state_list()
{
 set_state_list(new Array());
}

function get_state_list()
{
 try {
  var arr = eval(get_persistent_win().document.getElementById("state").innerHTML);
 } catch (e) {
  reset_state_list();
  arr = null;
 }
 if (arr == null) {
  return new Array();
 } else {
  return arr;
 }
}

function test_sound()
{
 if (play_sound("Fd") != 0) {
  alert("Did you hear the sound play? Otherwise check if sound applet is running properly.");
 }
}

function test_alerts()
{
 if (!get_persistent_win()) {
  return; // no persistent window open.
 }
 var plist = get_state_list();
 if (handle_alerts(newalertstate)) {
  alert("Couldn't handle alerts");
 }
}

function play_sound(key)
{
 if (get_persistent_win()) {
  var win = get_persistent_win();
  var feedback = win.document.getElementById("feedback");
  var isrun = is_papplet_running();
  if (isrun > 1) {
   get_persistent_win().document.getElementById("papplet").playsound("default");
   return 1;
  } else if (isrun == 0) {
   alert("Cannot use java applet for playing sound. Make sure java-plugin is installed in your browser.");
   return 0;
  } else {
   alert("Please wait for the java applet to start.");
   return 0;
  }
 } else {
  alert ("You need to open the sound alert window, by clicking on the speaker icon, before testing");
  return 0;
 }
}

// Check the persistent window for the state of the check/node... with
// the id
function get_current_alert_state(id)
{
 var plist = get_state_list();
 var state_len = plist.length;
 var i = 0;
 for (; i < state_len ; i++) {
  if (plist[i] == id) {
   return plist[i+1];
  }
  i++;
 }
 return state_unknown;
}

function set_current_alert_state(id, state)
{
 var plist = get_state_list();
 var state_len = plist.length;
 var i = 0;
 for (; i < state_len ; i++) {
  if (plist[i] == id) {
   plist[i+1] = state;
   set_state_list(plist);
   return;
  }
  i++;
 }

 plist.push(id);
 plist.push(state);
 set_state_list(plist);
}

function do_alert()
{
// get_persistent_win().document.getElementById("dbg").innerHTML = "alerting";
 play_sound();
}

// This function takes a list of states and ids ie. [id,state,id,state...]
// and stores the state in the persistent window. If the state has changed
// to the worse, compared to the existing state in the persistent window,
// a sound and/or visible notification is played/shown.
function handle_alerts(alerts)
{
 if (!get_persistent_win()) {
  alert("No persistent window available to play sound");
  return 1;
 }

 if (alerts.length % 2)
  return 1; // error

 has_alerted = 0;
 while (alerts.length) {
  var state = alerts.pop();
  var id = alerts.pop();
  var curstate = get_current_alert_state(id);
  if ((!has_alerted) && state > curstate && state > state_good) {
   do_alert();
  }
  if (curstate != state || curstate == state_unknown ) {
   set_current_alert_state(id,state);
  }
 }
 return 0;
}

function alert_no_java_win(win)
{
 win.document.write("<html><body><table><tr><td>Install java plugin to enable this feature</td></tr><tr><td><a href='#' onclick='window.close();'>[close]</a></td></tr></table></body></html>");
 win.document.close();
 top.opener.disable_tool_buttons();
}

function alert_no_java()
{
 alert_no_java_win(self);
}

function disable_tool_buttons() {
 // get list of tool buttons
 var list = document.getElementsBySelector("img.tal");
 if (!list){
   return;
 }

 var i = 0;
 for (i=0;element=list[i];i++){
  element.onclick = function() {}
  element.onmouseover = function() {}
  element.onmouseout = function() {}
  element.src = "toolapplet_disabledx.png";
 }
}

///////////////////////////////////////////////////////////////////////////
//
// Toggle state of the grouped layout in e.g. config pages.
//
var toggleState = new Array();

function toggleShown(id)
{
 if (typeof id == "string") {
  obj = getById(id);
 } else {
  obj = id;
  id = id.id;
 }
 if (obj) {
  disp = obj.style ? 0 : 1;
  seton = disp || obj.style.display == 'none';
  show(obj, seton);
  toggleState[id] = seton;
 }
}

///////////////////////////////////////////////////////////////////////////
//
// General applet stuff
//
function is_papplet_running()
{
 if (get_persistent_win())
  return get_persistent_win().papplet_is_running;
 else
  return false;
}

function is_lapplet_running()
{
 return self.lapplet_is_running;
}

function ensure_applet_running_win(name, num_tries, thedelay, win, feedback, okmsg)
{
 if (name == "papplet") {
  self.papplet_is_running = 1;
 } else {
  self.lapplet_is_running = 1;
 }
 if (num_tries > 0) {
  try {
   feedback.innerHTML = "Please wait, loading SysOrb applet...";
   if (win.document.getElementById(name).getAppletInfo() != "") {
    if (name == "papplet") {
     self.papplet_is_running = 2;
    } else {
     self.lapplet_is_running = 2;
    }
    if (okmsg != null) {
     feedback.innerHTML = okmsg;
    }
    return;
   }
  } catch (a) {}
  num_tries--;
 }

 if (num_tries > 0) {
  setTimeout(ensure_applet_running_win, 1000 * thedelay, name, num_tries, thedelay, win, feedback, okmsg);
 } else {
  if (name == "papplet") {
   self.papplet_is_running = 0;
  } else {
   self.lapplet_is_running = 0;
  }
/* feedback.innerHTML = "<h2>SysOrb</h2><p>Failed to load applet.</p>"; */
  alert_no_java(win);
 }
}

function ensure_applet_running(name, num_tries, thedelay)
{
 ensure_applet_running_win(name, num_tries, thedelay, self, getById("feedback"), null);
}

function getPixelWidth(id)
{
 return getById(id).offsetWidth;
}

// All this stuff because we want it to be reentrant
var animScriptArr = new Object();
var nextAnimId = 0;
var animate_speed = 30;
function animScriptsHelper(index, delay)
{
 if (animScriptArr[index] == null) {
  return;
 }
 script = animScriptArr[index].pop();
 if (script != null) {
// alert(script);
  eval(script);
 }
 if (animScriptArr[index].length) {
  setTimeout("animScriptsHelper(" + index + ", " + delay + ");", delay);
 } else {
  delete animScriptArr[index];
 }
}

function animScriptsHelperNoAnim(index, delay)
{
 if (animScriptArr[index] == null) {
  alert("no index " + index);
  return;
 }
 var i, len = animScriptArr[index].length;
 for (i = 0; i < len; i++) {
  eval(animScriptArr[index].pop());
 }
 delete animScriptArr[index];
}

function animateScripts(arr, delay)
{
 animScriptArr = arr;
 animScriptsHelperNoAnim(delay);
}

function setColor(r,g,b, arr)
{
 var i, alen = arr.length;
 for (i = 0; i < alen; i++) {
  if (arr[i] != null) {
   getById(arr[i]).style.color = "rgb(" + r + "," + g + "," + b + ")";
  }
 }
}

function animateInputTableRows(arr, delay)
{
 var i, arr_len = arr.length;
 new_animScriptArr = new Array();
 var animids = "new Array(";
 var delim = "";
 var ri = 0;
 var is_shown = !((getById(arr[0]).style ? 0 : 1) || getById(arr[0]).style.display == 'none');

 for (i = 0 ; i < arr_len; i++) {
  ri = i;
  if (is_shown) {
   ri = arr_len - (i+1);
  }
  if (arr[ri] != "") {
   // first the animated expansion
   new_animScriptArr[i] = 'toggleShown("' + arr[ri] + '");';
   // next the list of ids in order to animate the colors
   animids += delim + "'" + arr[ri] + "'";
   delim = ",";
  }
 }
 animids += ")";
 animScriptArr[nextAnimId++] = new_animScriptArr;
 animScriptsHelperNoAnim(nextAnimId-1, delay-25);
// animScriptsHelper(nextAnimId-1, delay);

 // build color fade
 var ci;
 var count = 4;
 var mult = Math.floor(256 / count);
 var colorAnimScripts = new Array();
 var cid = 0;
 for (ci = 0; ci < count; ci++) {
  if (is_shown) {
   cid = count - ci;
  } else {
   cid = ci;
  }
  colorAnimScripts[ci] = "setColor(" + Math.floor(cid*mult) + "," + Math.floor(cid*mult) + "," + Math.floor(cid*mult) + "," + animids + ");";
 }

 animScriptArr[nextAnimId++] = colorAnimScripts;
 animScriptsHelper(nextAnimId-1, delay);
}

// Freeze the sizes of the table with id tableid. Using the second
// row to determine the column widths.
function freezeTable(tableid)
{
 getById(tableid).style.width = getPixelWidth(tableid);
 var n_elems, elems = getById(tableid).getElementsByTagName("tr");
 n_elems = elems.length;
 if (n_elems <= 1) {
  // No rows except the header
// alert("no rows");
  return;
 }

 // first header TR then #text node then the first TR line
 if (elems[2] == null) {
  return;
 }
 var i, td_n_elems, td_elems = elems[2].getElementsByTagName("td");
 td_n_elems = td_elems.length;
 for (i = 0; i < td_n_elems; i++) {
  // freeze this td width
// alert ("Freezing " + td_elems[i]. + ": " + td_elems[i].offsetWidth);
  td_elems[i].style.width = td_elems[i].offsetWidth;
 }
}

var cur_highlight = 0;
function handleKeyPress(ev)
{
 var keyCode = ev.keyCode;
 var keyString = String.fromCharCode(ev.keyCode).toLowerCase();
 var cur = cur_highlight;

 delta = 0;
 if (keyString == "w") {
  delta = -1;
 } else if (keyString == "s") {
  delta = 1;
 }
 if (getById("optree" + cur ) != null) {
  getById("optree" + cur).style.background = "#FFFFFF";
 }
 if (getById("optree" + (cur+delta)) != null) {
  getById("optree" + (cur+delta)).style.background = "#FF0000";
  cur_highlight += delta;
 }
}

function enableKeyNavigation()
{
 document.onkeypress = handleKeyPress;
}

// enableKeyNavigation();
function changeImgByMatch(img, _match, _true, _false)
{
 var matches = 0;
 if (img.filtersrc) {
  // for IE5.5+ only. In order to handle transparent pngs
  matches = img.filtersrc.match(_match) == _match;
 } else {
  matches = img.src.match(_match) == _match;
 }
 if (matches) {
  img.src = _true;
 } else {
  img.src = _false;
 }
}

//var about_to_refresh = false;
var is_fullscreen = -1;
var timerId1 = -1;
var timerId2 = -1;
function update_refresh_counter(timeout)
{
 if (is_fullscreen == -1) {
  if (document.location.href.indexOf("viewdisabletop=yes") == -1) {
   is_fullscreen = 0;
  } else {
   is_fullscreen = 1;
  }
 }

 var rf;
 if (is_fullscreen == 1) {
  rf = getById("refreshbottom");
  if (rf && is_ie)
   rf.style.position = "absolute";
 } else {
  rf = getById("refresh");
 }

 if (rf && timeout > 0) {
  now = new Date();
  time_left = (timeout - Math.round((now - page_load_time) / 1000));
  new_text = "Time to refresh " + time_left + " sec ";
  if (new_text != rf.innerHTML)
   rf.innerHTML = new_text;
  if (time_left == -5)
   rf.style.color = 'red';
 }
 // When IE works someday do the following instead.
 // window.setTimeout(update_refresh_counter, 100, timeout, url);
 window.setTimeout("update_refresh_counter(" + timeout + ");", 100);
}

// Set Netscape up to run the "captureMousePosition" function whenever
// the mouse is moved. For Internet Explorer and Netscape 6, you can capture
// the movement a little easier.
if (document.layers) { // Netscape
 document.captureEvents(Event.MOUSEMOVE);
 document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
 document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
 document.onmousemove = captureMousePosition;
}
// Global variables
var xMousePos = 0; // Horizontal position of the mouse on the screen
var yMousePos = 0; // Vertical position of the mouse on the screen
var xMousePosMax = 0; // Width of the page
var yMousePosMax = 0; // Height of the page
var is_ie = navigator.userAgent.indexOf("MSIE") >= 0;
var extraMouseMove = [];

function captureMousePosition(e) {
 if (document.layers) {
  // When the page scrolls in Netscape, the event's mouse position
  // reflects the absolute position on the screen. innerHight/Width
  // is the position from the top/left of the screen that the user is
  // looking at. pageX/YOffset is the amount that the user has
  // scrolled into the page. So the values will be in relation to
  // each other as the total offsets into the page, no matter if
  // the user has scrolled or not.
  xMousePos = e.pageX;
  yMousePos = e.pageY;
  xMousePosMax = window.innerWidth+window.pageXOffset;
  yMousePosMax = window.innerHeight+window.pageYOffset;
 } else if (document.getElementById && !is_ie) {
  // Netscape 6 behaves the same as Netscape 4 in this regard
  xMousePos = e.pageX;
  yMousePos = e.pageY;
  xMousePosMax = window.innerWidth+window.pageXOffset;
  yMousePosMax = window.innerHeight+window.pageYOffset;
 } else if (document.all) {
  // When the page scrolls in IE, the event's mouse position
  // reflects the position from the top/left of the screen the
  // user is looking at. scrollLeft/Top is the amount the user
  // has scrolled into the page. clientWidth/Height is the height/
  // width of the current page the user is looking at. So, to be
  // consistent with Netscape (above), add the scroll offsets to
  // both so we end up with an absolute value on the page, no
  // matter if the user has scrolled or not.
  xMousePos = window.event.x+document.body.scrollLeft;
  yMousePos = window.event.y+document.body.scrollTop;
  xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
  yMousePosMax = document.body.clientHeight+document.body.scrollTop;
 }
 for (var i = 0; i < extraMouseMove.length; ++i)
  extraMouseMove[i](e);
// getById("dbg").innerHTML = "xpos" + xMousePos;
}

function get_root_name(imgname)
{
 var di = imgname.indexOf("_over.png");
 if (di == -1) {
  var di = imgname.indexOf("_disabled.png");
 }
 var res = new Object();
 var rootname = "";
 if (di == -1) {
  di = imgname.indexOf(".png");
  rootname = imgname.substr(0,di); 
 } else {
  rootname = imgname.substr(0,di);
 }
 return rootname;
}

function get_over_and_out_name(imgname)
{
 var rootname = get_root_name(imgname);
 var res = new Object();
 res.over = rootname + "_over.png";
 res.out = rootname + ".png";
 return res;
}

function set_action_state(myobj, rootimg, set_off) {
 if (set_off) {
  myobj.src = rootimg + '_disabled.png';
  myobj.is_disabled = true;
  myobj.onmouseover = '';
  myobj.onmouseout = '';
  myobj.disabled = 1;
  objModToOrigClass(myobj, 'cursordefault', 'cursorpointer');
 } else {
  myobj.src = rootimg + '.png';
  myobj.is_disabled = false;
  myobj.onmouseover = 'this.src = "' + rootimg + '_over.png"';
  myobj.onmouseout = 'this.src = "' + rootimg + '.png"';
  myobj.disabled = 0;
  objModToOrigClass(myobj, 'cursorpointer', 'cursordefault');
 }
}

function set_action_state2(obj, is_on)
{
// alert("Test " + obj.id + " " +is_on);
// var obj = ev.dependency;
 var imgname = obj.src;
 var di = imgname.indexOf("_disabled.png");
 var cur_enabled = 1;
 if (di != -1) {
  cur_enabled = 0;
 }

 var newsrc = "";
 if (!cur_enabled && is_on) {
  // Currently not enabled button, but should be.
  img = imgname.substr(0,di);
  obj.src = img + '.png';
  obj.onmouseover = 'this.src = "' + img + '_over.png"';
  obj.onmouseout = 'this.src = "' + img + '.png"';
  obj.disabled = 0;
  objModToOrigClass(obj, 'cursorpointer', 'cursordefault');
 } else if (cur_enabled && !is_on) {
  // Currently enabled button, but should not be.
  di = imgname.indexOf(".png");
  img = imgname.substr(0,di); 
  obj.src = img + '_disabled.png';
  obj.onmouseover = '';
  obj.onmouseout = '';
  obj.disabled = 1;
  objModToOrigClass(obj, 'cursordefault', 'cursorpointer');
 }
}

//
// Helper to shorten javascript on main page
//
function toggleSiblings(pn)
{
 while (pn.nextSibling) {
  // Check that it's a <tr> sibling, since FF has
  // text nodes between all tags
  if (pn.nextSibling.tagName) {
      toggleShown(pn.nextSibling);
  }
  pn = pn.nextSibling;
 }
}

function setGenericConfigLineEnabled(row, set_enabled)
{
 // Check that it's a <tr> sibling, since FF has
 // text nodes between all tags
 var max_next_siblings = 4;
 while (!row.tagName && max_next_siblings--) {
  row = row.nextSibling;
 }
 if (!max_next_siblings) {
  return;
 }

 // First the label/units
 if (set_enabled) {
  objModToOrigClass(row, "", "disabled");
 } else {
  objModToOrigClass(row, "disabled", "");
 }

 // Now all the input/select/textareas must be disabled
 // Also remember last value in order to be able to restore the
 // last know value if the user reclicks override checkbox
 var a = row.getElementsByTagName("INPUT");
 var i = 0;
 for (i = 0; i < a.length; i++) {
  var el = a[i];
  // Do not disable the override checkbox
  if (el.origvalue == null) {
   el.origvalue = el.getAttribute("ncvalue");
  }
  if (el.className != "ovr") {
   el.disabled = !set_enabled;
   if (!el.disabled && el.origvalue == null) {
    if (el.type == "checkbox" || el.type == "radio") {
     el.origvalue = el.checked;
    } else {
     el.origvalue = el.value;
    }
   } else
   if (el.disabled && el.origvalue != null) {
    if (el.type == "checkbox" || el.type == "radio") {
     el.checked = parseInt(el.origvalue);
    } else {
     el.value = el.origvalue;
    }
   }
  } else {
// alert(el.id);
  }
 }

 var a = row.getElementsByTagName("SELECT");
 var i = 0;
 for (i = 0; i < a.length; i++) {
  var ta = a[i];
  ta.disabled = !set_enabled;
  if (ta.origvalue == null) {
   ta.origvalue = ta.getAttribute("ncvalue");
  }
  if (!ta.disabled && ta.origvalue == null) {
   ta.origvalue = ta.value;
   for (j=0;opt=ta.options[j];j++) {
    if (opt.selected) {
     ta.origvalue = j;
    }
   }
  } else if (ta.disabled && ta.origvalue != null) {
   if (ta.origvalue == null || ta.origvalue == "") {
    ta.origvalue = "0";
   }
   ta.options[parseInt(ta.origvalue)].selected = true;
  }
 }

 var a = row.getElementsByTagName("TEXTAREA");
 var i = 0;
 for (i = 0; i < a.length; i++) {
  var ta = a[i];
  ta.disabled = !set_enabled;
  if (ta.origvalue == null) {
   ta.origvalue = ta.getAttribute("ncvalue");
  }
  if (!ta.disabled && ta.origvalue == null) {
   ta.origvalue = ta.value;
  } else
  if (ta.disabled && ta.origvalue != null) {
   ta.value = ta.origvalue;
  }
 }
}

function openWin(x, setbars, height, width)
{
 var bars = "no";
 if (setbars) {
  bars = "yes";
 }
 var opts = "menubar=" + bars
  + ",scrollbars=yes,toolbars=" + bars
  + ",location=no,status=no,directories=no,"
  + "resizable=yes,scrollbars=yes";
 if (width)
  opts = opts + ",width=" + width;
 if (height)
  opts = opts + ",height=" + height;
 window.open(x, "_blank", opts);
}

function toolwin(x, ypos, xpos)
{
 var tappletwin = newWindow(x,'toolwindow',
  'width=270,top=' + ypos + ','
  + 'left=' + xpos + ',resizable,scrollbars,height=360');
 tappletwin.focus();
 return false;
}

function setSelectedDate(y, m, d, divname)
{
 var selected = new Date();
 selected.setFullYear(y, m - 1, d);

 var name = divname.substring(0, divname.length - 3);
 var o = getById(name + "::edit");
 o.value = formatDate(selected, "yyyy/MM/dd");
 if (o.onchange)
  o.onchange();
}

function showCalendar(e, img)
{
 now = new Date();
 now.setDate(now.getDate() - 1);
 var cal = new CalendarPopup(img.id + 'div');
 cal.addDisabledDates(null, formatDate(now, "yyyy-MM-dd"));
 cal.showYearNavigation();
 cal.autoHideEnabled = false;
 cal.offsetX = 0;
 cal.offsetY = 0;
 cal.setReturnFunction("setSelectedDate");
 if (cal.shown) {
  cal.hideCalendar();
 } else {
  var o = getById(img.id + '::edit');
  if (o.disabled)
   return;
  cal.currentDate = new Date(getDateFromFormat(o.value, "yyyy/MM/dd"));
  if (cal.currentDate.getYear() < 100)
  cal.currentDate = new Date();
  cal.showCalendar();
 }
}

function setSelectedTime(h, m, divname)
{
 var name = divname.substring(0, divname.length - 3);
 var o = getById(name + "::edit");
 o.value = twodigit_number(h) + ':' + twodigit_number(m);
 if (o.onchange)
  o.onchange();
}

function showTimeSel(e, img)
{
 var timesel = new TimeSelPopup(img.id + 'div');
 timesel.offsetX = 0;
 timesel.offsetY = 0;
 timesel.setReturnFunction("setSelectedTime");
 if (timesel.shown) {
  timesel.hideTimeSel();
 } else {
  var o = getById(img.id + '::edit');
  if (o.disabled)
   return;
  timesel.currentHour = o.value.substr(0, o.value.indexOf(':'));
  timesel.currentMinute = o.value.substr(o.value.indexOf(':') + 1);
  timesel.showTimeSel();
 }
}

function focusId(id)
{
 getById(id).focus();
}

//
// Table group folding
//
var group_first = new Object();
var group_rows = new Object();
var group_collapsed = new Object();

function fold_group(id)
{
 var row = getById(group_first[id]);
 var num_rows = group_rows[id];
 var collapsing = !group_collapsed[id];
 group_collapsed[id] = collapsing;

 var i = 0;
 for (; i < num_rows ; i++) {
  if (!row["collapse_count"])
   row["collapse_count"] = 0;
  if (collapsing)
   row["collapse_count"] += 1;
  else
   row["collapse_count"] -= 1;
  show(row, row["collapse_count"] == 0);
  do {
   row = row.nextSibling;
   // Check that it's a <tr> sibling, since FF has
   // text nodes between all tags
  } while (row && !row.tagName);
 }
 return collapsing;
}

// Get x position for image
function image_x(image)
{
 var x = image.x;
 return x===undefined ? findPosViaOffsets(image)[0] : x;
}

// Get y position for image
function image_y(image)
{
 var y = image.y;
 return y===undefined ? findPosViaOffsets(image)[1] : y;
}

// Find offset for object obj.
//
// When an object has been positioned absolutely then position can be
// found with left/top on style (e.g. element.style.left), but for
// non-positioned objects this function can be used.
//
// Needed for Internet Explorer 7 support: Their image object does not
// support getting x and y
function findPosViaOffsets(obj)
{
 var posX = obj.offsetLeft;
 var posY = obj.offsetTop;
 while(obj.offsetParent) {
  if(obj==document.getElementsByTagName('body')[0]){break}
  else {
   posX=posX+obj.offsetParent.offsetLeft;
   posY=posY+obj.offsetParent.offsetTop;
   obj=obj.offsetParent;
  }
 }
 var posArray=[posX,posY]
 return posArray;
}

