/* Shared Javascript Library

This file should contain only *generic* functions used on *multiple* pages.
Specialized Javascript used only by a single page should reside on that page.

Other JavaScript Libraries:

  Action Results -- Javascript functions to mimic server-side Action Results
  messages, such as setInfo(), setWarn(), setError(), and setConfirm() are in:
  ~/godspeed/ui/webui/common-packages/navigation/ActionResults.tmpl

*/

// Standard method always called before the closing BODY tag.
function bodyOnLoad() {
  //Test confirm dialog
  //setYesNoConfirm("Ist das gut?","alert('Gut!')");
}

// Simply a more compact method call.
function getObj(Id) {
  obj = document.getElementById(Id);
  return obj
}

// Confirmation Dialog Methods
function confirmDialogInit() {
  document.write('\
    <div id="confirm_dialog" style="display: none" \
      <table align="center" style="height:100%"> \
        <tr> \
          <td id="confirm_symbol">?</td> \
          <td style="text-align:center;padding-right:40px;"> \
          <form id="confirm_form" name="confirm_form"> \
            <span id="confirm_message">message</span> \
          </form> \
        </td> \
      </tr></table> \
    </div>'); 
}
confirmDialogInit();

function confirmDialogResize(d) {
  var width = 450;
  d.style.width = width + 'px';
  d.style.height = '150px';
  d.style.left = (screen.width/2 - width/2 - 50) + 'px';  // centered
  d.style.top = d.style.height;
}

var isConfirmDialogShown = false;
function confirmDialogHide() {
  if (isConfirmDialogShown) {
    var d = getObj('confirm_dialog');
    if(d) d.style.display = 'none';
  }
}

// Create a customized confirmation dialog.
// Parameters must not contain double-quotes.
function setConfirm(message, buttonCancel, buttonOk, onCancel, onOk) {
  var d = getObj('confirm_dialog');
  if(d) {
    d.style.display = 'none';
    isConfirmDialogShown = false;
    var din = getObj('confirm_message');
    din.innerHTML =   message + '<br><br><br>'
      + '<input type="button" class="button" value="'+buttonCancel+'" '
      + 'onClick="'+onCancel+'"> '
      + '&nbsp;&nbsp;&nbsp;'
      + '<input id="confirm_ok" type="button"'
      + 'value="'+buttonOk+'" class="button" '
      + 'onClick="'+onOk+'">';
    confirmDialogResize(d);
    document.onclick = confirmDialogHide;
    d.style.display = '';
    setTimeout("isConfirmDialogShown = true;getObj('confirm_ok').focus();",50);
  }
}

// Create a Yes/No confirmation dialog.
// Pressing the Yes button will execute the javascript passed in buttonOk.
// buttonOk must not contain double-quotes.
function setYesNoConfirm(message, buttonOk) {
  setConfirm(message, "No", "Yes", "confirmDialogHide()", buttonOk)
}



// Contextual Bubble Dialog Methods
function bubbleDialogInit() {
  document.write('\
    <div id="bubble_dialog" style="display: none;"> \
      <div id="bubble_header"> \
        <span style="float: right; cursor: pointer;">X</span> \
        <span id="bubble_title">Help</span> \
      </div> \
      <div id="bubble_message">message</div> \
    </div>'); 
}
bubbleDialogInit();

function bubbleDialogResize(d,ctrl) {
  var width = 200;
  d.style.width = width + 'px';
  //d.style.height = '120px';

  // Aggregate offsets of parents beneath BODY.
  var left = 25;
  var top = -3; 
  var aTag = ctrl;
  do {
    left += aTag.offsetLeft;
    top  += aTag.offsetTop;
    aTag     = aTag.offsetParent;
  } while (aTag.tagName != 'BODY');
  
  d.style.left = left + 'px';
  d.style.top = top + 'px';
}

var isBubbleDialogShown = false;
function bubbleDialogHide() {
  if (isBubbleDialogShown) {
    var d = getObj('bubble_dialog');
    if(d) d.style.display = 'none';
  }
}

// Create a customized bubble dialog.
// Parameters must not contain double-quotes.
function bubbleDialog(ctrl, type, title, message) {
  var d = getObj('bubble_dialog');
  if(d) {
    d.style.display = 'none';
    isBubbleDialogShown = false;
    var dh = getObj('bubble_header');
    dh.className = 'bubble-header-info';
    if(type == 'error') dh.className = 'bubble-header-error';
    var dt = getObj('bubble_title');
    dt.innerHTML =  title;
    var dm = getObj('bubble_message');
    dm.className = 'bubble-message-info';
    if(type == 'error') dm.className = 'bubble-message-error';
    dm.innerHTML =  message;
    bubbleDialogResize(d,ctrl);
    document.onclick = bubbleDialogHide;
    d.style.display = '';
    setTimeout("isBubbleDialogShown = true");
  }
}

function bubbleInfo(ctrl, title, message) {
  bubbleDialog(ctrl, 'info', title, message) 
}

function bubbleError(ctrl, title, message) {
  bubbleDialog(ctrl, 'error', title, message) 
}



// Trap the ENTER key for form submission onKeyPress within a text-input field.
// Do not use this for onKeyUp because that breaks multilanguage IME support.
var prevKeyCode = 0;
function doTextAction(event, form, action) {
  if (event.keyCode == 13) {
    if(action != '')
      return doClickAction(form, action);
    else
      return false;
  }
  prevKeyCode = event.keyCode;
}

// Make an input-button work like an input-submit.
//  form - form object
//  action - action name
//  sf - bool option whether to submit form or not (default true)
//
// This example allows different actions, default action on "Enter" press,
// in IE prevents multiple POSTs on submitting
// via submit button or "Enter" press:
//
// <form name="form" id="form" action="...">
//   <input type="hidden" name="action" value="MyDefaultAction" />
//    ...
//   <input type="button" class="button"
//       onclick="doClickAction(this.form, 'Cancel');" value="Cancel" />
//   <input type="button" class="button"
//       onclick="doClickAction(this.form, 'AnotherAction');"
//       value="Another action" />
//   <input type="submit"
//       onclick="doClickAction(this.form, 'MyDefaultAction', false);" />
// </form>

// This example allows different actions, default action on "Enter" press
// (except IE), prompts,
// in IE prevents multiple POSTs on submitting
// via submit button or "Enter" press:
// TODO: in IE submit on "Enter" press
//
// <form name="form" id="form" action="..." onsubmit="return false">
//   <input type="hidden" name="action" value="MyDefaultAction" />
//    ...
//   <input type="button" class="button"
//       onclick="doClickAction(this.form, 'Cancel');" value="Cancel" />
//   <input type="button" class="button"
//       onclick="setYesNoConfirm('Another prompt', 'doClickAction(f, \'AnotherAction\');');"
//       value="Another action" />
//   <input type="submit"
//       onclick="setYesNoConfirm('Default prompt', 'doClickAction(f, \'MyDefaultAction\');');" />
// </form>
// <script language="javascript"><!--
//  f = document.forms['form'];
// // -->
// </script>

function doClickAction(form, action, sf) {
  form.elements['action'].value = action;
  if (sf == null) sf = true;
  if (sf) {
    form.submit();
  }
  
  return false;
}

// Submit only with a confirmation message.
var _doConfirm_form;
var _doConfirm_action;
function doConfirmClickAction(form, action, msg) {
  _doConfirm_form = form;
  _doConfirm_action = action;
  setConfirm(msg, "Cancel", "OK", "setInfo('')",
    "doClickAction(_doConfirm_form, _doConfirm_action)")
}

function goPage(page, param) {
  location.href="?pg=" + page + param;
}

// Enable or disable an object, and set the background color.
function set_obj_enabled(obj, enabled) {
  obj.disabled = !enabled;

  if (!enabled) {
    if (obj.type != 'radio' && obj.type != 'checkbox') {
      obj.style.color = '#999999';
      obj.style.backgroundColor = '#E0E0E0';
    }
  }
  else if (obj.type == 'button' || obj.type == 'submit') {
    obj.style.color = '#FFFFFF';
    obj.style.background = '#666699';

  }
  else {
    obj.style.color = '';
    obj.style.backgroundColor = ''; 
  }
}

// Set disabled attribute and style for an input element. 
function set_enabled(id, enabled, doFocus) {
  var obj = document.getElementById(id);
  if (!obj && document.forms['form'])
    obj = document.forms['form'].elements[id];
  if (obj) {
    if (obj.type == 'radio') {
      // This fixes a rather annoying javascript bug with radios.
      // The radio returned by getElementById has no length property. 
      obj = obj.form[obj.id];
      for (var i=0; i<obj.length; i++)
        set_obj_enabled(obj[i], enabled);
    } 
    else
      set_obj_enabled(obj, enabled);
    if (enabled && doFocus && (obj.type == 'text' || obj.type == 'textarea'))
      obj.focus();
  }
}

// Check a checkbox field by id. Returns true if the checkbox was set. 
function set_checkbox(checkboxId) {
  var obj = document.getElementById(checkboxId);
  if (!obj && document.forms['form'])
    obj = document.forms['form'].elements[checkboxId];
  if (obj && !obj.disabled) {
    obj.checked = true; 
    return true;
  }
  return false;
}

// Check a checkbox field by id if prerequisite is met. 
function set_checkbox_preq(checkboxId, preq) {
  var obj = document.getElementById(preq);
  if (obj && obj.disabled)
    return;
  else {
    obj = document.getElementById(checkboxId);
    if (obj) 
      set_obj_checked(obj);
  }
}

// Check a specific radio field. 
function set_radio(obj, index) {
  obj[index].checked = true;
}
// Check a checkbox or radio object. 
function set_obj_checked(obj) {
  obj.checked = true;
}

// Enable an input field. 
function enable_input(inputId) {
  set_enabled(inputId, true, true); 
}

// Disable an input field. 
function disable_input(inputId) {
  set_enabled(inputId, false, false); 
}

// Enable an input field without setting the focus. 
function enable_input_nofocus(inputId) {
  set_enabled(inputId, true, false); 
}

// Toggle an input field  enabled/disabled based on checkbox setting. 
function toggle_input(inputId, checked) {
  set_enabled(inputId, checked, true);
}

// Toggle an input field without setting the focus. 
function toggle_input_nofocus(inputId, checked) {
  set_enabled(inputId, checked, false);
}

// Check all checkboxes for the form. 
function check_all(form, checked) {
  var elts = form.elements;
  var len = elts.length;
  for (i = 0; i < len; i++) {
      e = elts[i];
      if (e.name=='senders[]')
          e.checked = checked;
  }
}

// Sort a select list alphabetically.
function sort_select(sel) {
if (sel.options == null || sel.options.length <= 1)
    return;

  var o = new Array();
  for (var i = 0; i < sel.options.length; i++)
    o[o.length] = new Option(sel.options[i].text, sel.options[i].value, 
                             sel.options[i].defaultSelected, 
                             sel.options[i].selected);

  // Null-proof sort
  o = o.sort(function(a,b) { 
               if ((a.text+"") < (b.text+""))
                 return -1;
               if ((a.text+"") > (b.text+""))
                 return 1;
               return 0;
             });

  for (var i = 0; i < o.length; i++)
    sel.options[i] = new Option(o[i].text, o[i].value, 
                                o[i].defaultSelected, o[i].selected);
}

// Takes two select lists, and moves selected items from one to the other.
function select_move(from, to) {
  for (var i = 0; i < from.options.length;) {
    var o = from.options[i];
    if (o.selected) {
      to[to.length] = new Option(o.text, o.value, false, false);
      from.options[i] = null;
    } 
    else
      i++;
  }
  sort_select(from);
  sort_select(to);
  return true;
}

// Mark options in a select (multiple) list as selected.
function select_all(sel) {
  if (sel.options == null)
    return true;
  for (i = 0; i < sel.options.length; i++)
    sel.options[i].selected = true;
  return true;
}

function resetElement(elementId, setting) {
  var obj = getObj(elementId);
  resetElementObj(obj, setting);
}

function resetElementObj(obj, setting) {
  // Recursively resets all form elements inside a span or div element.
  // Setting can be hide, show, disable, enable  
  // Used a hack to detect a HTMLSpanElement in IE -
  // name all spans with a prefix of "span_".  Same for table, tbody and tr.
  var n = obj.childNodes.length;
  for(var i=0;i<n;i++) {
    child = obj.childNodes[i];

    if (
        (child.type=='text') || (child.type=='select-one') || 
        (child.type=='button') || (child.type=='textarea') ||
        (child.type=='label') || (child.type=='radio') ||
        (child.type=='checkbox')
      ) {
      switch (setting) {
        case 'hide':
          hideObj(child);
          break;
        case 'show':
          showObj(child);
          break;
        case 'enable':
          set_obj_enabled(child,true);
          break;
        case 'disable':
          set_obj_enabled(child,false);
	case 'clear_err':
	  child.className = '';
      }
    }
    else if (child.id) {
      var string = child.id.toString().split("_");
      if (string[0]=='err' && setting == 'clear_err') {
        hideObj(child);
	}
      else if (string[0]=='td') {
  	hideObj(child);
        resetElementObj(child, setting);
      }
      else if ((string[0]=='tr') || (string[0]=='txt'))
        hideObj(child);
      else
        resetElementObj(child, setting);
    }
    else if (child){
      if (child.childNodes)
        resetElementObj(child, setting);
    }
  }
}

function hideObj(obj) {
  if(obj) {
    obj.style.display = 'none';
    obj.style.height='0px';
  }
}

function showObj(obj) {
  if(obj) {
    obj.style.display = '';
    obj.style.height='';
  }
}

function popUp(url, w, h) {
  nw = window.open(url, 'newWin',
    'width=' + w + ',height=' + h + ',menubar=1,resizable=1');
  nw.focus();
}


// Make a portion of the page flicker to emphasize that it has changed.
var flicker_yellow = new Array('#eeeeee',
  '#eeeeee','#efefea','#f0f0e6','#f1f1e2',
  '#f2f2de','#f3f3da','#f4f4d6','#f5f5d2',
  '#f6f6ce','#f7f7ca','#f8f8c6','#f9f9c2',
  '#fafabe','#fbfbba','#fcfcb6','#fdfdb2',
  '#fefeae','#ffffaa','#ffffaa');
var flicker_red = new Array('#eeeeee',
  '#eeeeee','#efeaea','#f0e6e6','#f1e2e2',
  '#f2dede','#f3dada','#f4d6d6','#f5d2d2',
  '#f6cece','#f7caca','#f8c6c6','#f9c2c2',
  '#fabebe','#fbbaba','#fcb6b6','#fdb2b2',
  '#feaeae','#ffaaaa','#ffaaaa');
var flicker_colors;
var flicker_end_color;
var flicker_up;
var flicker_loops;
var flicker_id;

function flicker(id, color_choice, end_color) {
  flicker_id = id;
  flicker_end_color = end_color;
  flicker_colors = flicker_yellow;
  if(color_choice == 'red') flicker_colors = flicker_red;
  flicker_loops = 2;
  flicker_up = true;
  flicker_loop(0);
}

function flicker_loop(i) {
  var delay = 40;
  if(flicker_id == '' ) return;
  var flicker_obj = getObj(flicker_id);
  flicker_obj.style.backgroundColor = flicker_colors[i];
  if (flicker_up) {
    if (i++ < flicker_colors.length) {
      setTimeout("flicker_loop(" + i + ")", delay);
    }
    else {
      flicker_up = false;
      flicker_loop(--i);
    }
  }
  else {
    if (i-- > 0) {
      setTimeout("flicker_loop(" + i + ")", delay);
    }
    else {
      if (--flicker_loops > 0) {
        flicker_up = true;
        flicker_loop(0);
      }
      else {
        flicker_obj.style.backgroundColor = flicker_end_color;
      }
    }
  }
}











// widget.itable functions
function itable_del(e, id) {
  var t = document.getElementById(id);
  var r = itable_get_TRow(e);
  var i = 0;
  for (i = 0; i < t.rows.length;++i) {
    if (t.rows[i] == r) {
      break;
    }
  }
  if (i > 0) {
    t.deleteRow(i);
  } else {
    alert('Can not delete row');
  }
  
  return false;
}

function itable_get_TRow(e) {
  return e.parentNode.parentNode;
}

function itable_addRow(id, del) {
  var t = document.getElementById(id);
  var _r = t.rows[t.rows.length-1];
  var row;
  //handling special rows
  if (_r.id != id + '-footer') {
    row    = t.insertRow(t.rows.length);
  } else {
    row    = t.insertRow(t.rows.length-1);
  }
  
  var i;
  for (i in itable_col_defs[id]) {
    var cell = row.insertCell(i)
    var el = document.createElement('input');
    var fld = itable_col_defs[id][i];
    for (j in fld) {
      if (j == 'id') {
        var v = id + '['+itable_next_counter(id)+']['+fld[j]+']';
        el.setAttribute('name', v);
        el.setAttribute('id', v);
      } else {
        el.setAttribute(j, fld[j]);
      }
      
    }
    cell.appendChild(el);
  }
  var cell = row.insertCell(row.childNodes.length);
  cell.setAttribute('align', 'center');
  cell.innerHTML = del;
  return false;
}

function itable_next_counter(id) {
  return ++itable_row_counter[id];
}


var itable_col_defs = new Array();
var itable_row_counter = new Array();


