// JavaScript util for EogS - rVR by Gunni Rode - http://www.tietoenator.com

var commands         = {};
var fields           = {};
var activatedCommand = null;
var busy             = false;
var notified         = false;

//
function commandActivated(commandId) {
  if (!(busy = (activatedCommand != null))) {
    setCommand(activatedCommand = resolveCommandId(commandId));
    return commandActivatedHandler(activatedCommand);
  }
  return false;
}

// Default implementation...
function commandActivatedHandler(commandId) {
  return true;
}

//
function commandInactive(commandId) {
  commandInactiveHandler(resolveCommandId(commandId));
  return false;
}

// Default implementation...
function commandInactiveHandler(commandId) {
}

//
function selectChanged(elementOrId) {
  return selectChangedHandler(resolveElement(elementOrId));
}

// Default implementation...
function selectChangedHandler(element) {
  return true;
}

// Display selected value...
function selectChangedDisplay(elementOrId) {
  var e = resolveElement(elementOrId);
  var div = document.getElementById(e.name + "_display_text");
  if (div) {
    if ((e.selectedIndex != -1) && (e.options[e.selectedIndex].value) && (div.innerText = e.options[e.selectedIndex].text)) {
      var tr = document.getElementById(e.name + "_display");
      if (!tr.onclick) {
        addHandler(tr, "onclick", function() {hide(tr); return false;});
      }
      show(e.name + "_display");
    } else {
      hide(e.name + "_display");
    }
  }
}

//
function resolveElement(elementOrId) {
  var e = elementOrId;
  if (typeof(elementOrId) == 'string') {
    e = document.getElementById(elementOrId);
  }
  return e;
}

//
function resolveCommandId(commandId) {
  if (commandId) {
    if (commandId.substr(0, 8) != 'command_') {
      commandId = 'command_' + commandId;
    }
    return commandId;
  }
  return null;
}

//
function check(commandId, id, defaultValue, type, message) {
  if (arguments.length) {
    var field = fields[id];
    if (field == null) {
      fields[id] = field = {id:       id,
                            value:    defaultValue,
                            types:    [],
                            messages: []};
    }
    field.types.push(type);
    field.messages.push(message);

    if (commandId) {
      var list = commands[commandId = resolveCommandId(commandId)];
      if (list == null) {
        commands[commandId] = list = [];
      }
      list.push(field);
    }
  } else {
    if (busy) {
      return false;
    }
    var list = commands[activatedCommand];
    if (list == null) {
      return true;
    }
    for (var i = 0; i < list.length; i++) {
      var field = list[i];
      var error = validate(field.id, true);
      if (error != -1) {
        alert(field.messages[error]);
        activatedCommand = null; // Did not submit...
        return false;
      }
    }
    deactivate();
    return true;
  }
}

//
function validate(id, dontClear) {
  var field = fields[id];
  if (field == null) return -1;
  var e = document.getElementById(field.id);
  if (e == null) return -1;
  // Remove handler...
  e.onkeydown = null;
  e.onfocus   = null;
  // Default value for the field...
  var regEx = new RegExp(field.value, "i");
  var original = e.value;
  // Skip leading or trailing spaces...
  var value = original.replace(/^\s+|\s+$/, "");
  // Reduce two or more spaces to a single one...
  value = value.replace(/\s+/g, " ");
  // Remove original value...
  value = value.replace(regEx, "");
  // Now perform the desired validation...
  var error = -1;
  for (var i = 0; error == -1 && i < field.types.length; i++) {
    switch (field.types[i]) {
      case 'empty': {
        if (value == "") {
          error = i;
        }
        break;
      }
      case 'numeric': {
        if (value.replace(/\d|\-/g, "")) {
          error = i;
        }
        break;
      }
      // Do nothing client side...
      default:
      case 'date': {
      }
    }
  }
  if ((!dontClear) && (original != value)) {
    // Update value?...
    switch (e.tagName.toLowerCase()) {
      case 'input': {
        e.value = value;
        break;
      }
      default:
    }
  }
  hide(field.id + "_error");
  hide(field.id + "_warning");
  return error;
}

//
function deactivate(commandId) {
  commandId = resolveCommandId(commandId);

  // Update commands...
  var elements = document.getElementsByTagName("input");
  if (elements == null) {
    return;
  }
  for (var i = 0; i < elements.length; i++) {
    var e = elements[i];
    if (((e.type == 'submit') || (e.type == 'reset')) && (e.className == 'button')) {
      if (!commandId || e.name == commandId) {
        e.className = 'buttoninactive';
        if (e._onclick == null) {
          e._onclick = e.onclick;
        }
        e.onclick   = function() {
                        return false;
                      };
      }
    }
  }
}

//
function activate(commandId) {
  commandId = resolveCommandId(commandId);
  // Update commands...
  var elements = document.getElementsByTagName("input");
  if (elements == null) {
    return;
  }
  for (var i = 0; i < elements.length; i++) {
    var e = elements[i];
    if (((e.type == 'submit') || (e.type == 'reset')) && (e.className == 'buttoninactive')) {
      if (!commandId || e.name == commandId) {
        e.className = 'button';
        e.onclick = e._onclick;
      }
    }
  }
}

//
function setCommand(commandId) {
  // Assume a single form...
  var form = document.forms[0];
  var id   = resolveCommandId(commandId);
  // Add form "value", i.e., the hidden field representing the
  // form value when submitted; the value will contain the
  // command id of the command activated...

  // NOTE: cannot use form name, since form elements may have
  //       an id of 'name'! Assumes no form elements have the
  //       name 'id'...
  var elements = document.getElementsByName(form.id); // form and hidden element, if any...
  for (var i = 0; i < elements.length; i++) {
    var e = elements[i];
    if ((e.tagName.toLowerCase() == 'input') &&
        (e.type.toLowerCase()    == 'hidden')) {
      e.value = id;
      break;
    }
  }
  // Update action (if need be)...
  form.action = getCommandAction(id);
}

//
function getCommandAction(commandId) {
  var e = document.getElementById(commandId = resolveCommandId(commandId));
  if (e) {
    var a = document.getElementById(commandId + "_action");
    if (a) {
      return a.value;
    }
  }
  return document.forms[0].action; // default...
}

//
function notifyError(id, message, commandId) {
  if (notified) {
    return;
  }
  notified = true;
  addHandler("onload", function () {
                         if (commandId) {
                           commandId = resolveCommandId(commandId);
                           if (confirm(message)) {
//                             var e = document.createElement("input");
//                                 e.type  = 'hidden';
//                                 e.name  = commandId;
//                                 e.value = document.getElementById(commandId).value;
//                             document.forms[0].appendChild(e);
                             setCommand(commandId);
                             document.forms[0].submit();
                           } else {
                             focus(id);
                           }
                         } else {
                           alert(message);
                           focus(id);
                         }
                       });
}

//
function focus(elementOrId) {
  if (elementOrId) {
    var e = resolveElement(elementOrId);
    try {
      e.focus();
      e.select();
    } catch (exception) {
    }
  }
}

//
function show(elementOrId) {
  var e = resolveElement(elementOrId);
  if (e != null) {
    e.style.display = 'block';
  }
}

//
function hide(elementOrId) {
  var e = resolveElement(elementOrId);
  if (e != null) {
    e.style.display = 'none';
  }
}

//
function toggle(elementOrId) {
  var e = resolveElement(elementOrId);
  if (e != null) {
    if (e.style.display == 'none') {
      e.style.display = 'block';
      return true;
    } else {
      e.style.display = 'none';
      return false;
    }
  }
}

var windows = {};

//
function showPage(pageId, windowId, w, h) {
  return showWindow(pageId, windowId, w, h);
}

//
function showCommand(commandId, windowId, w, h) {
  return showWindow(getCommandAction(commandId), windowId, w, h);
}

//
function showWindow(action, windowId, w, h) {
  var id     = windowId ? windowId : 'window';
  var width  = w        ? w        : 630;
  var height = h        ? h        : 800;
  if (id.substr(0, 8) != 'revireg_') {
    id = 'revireg_' + id;
  }
  var win = windows[id];
  if ((win != null) && (!win.closed)) {
    if ((win.location.href.search(action) != -1) || (confirm("Vinduet er ved at vise en anden side!\n\nVil du gå væk fra den?"))) {
      win.location.href = action;
      win.resizeTo(width, height);
    }
  } else {
    windows[id] = win = window.open(action, id, 'width=' + width + ',height=' + height + ',scrollbars,toolbar=no,status=no,menubar=no,resizable=no');
  }
  win.focus();
  return false;
}

//
function addHandler() {
  var i = (typeof(arguments[0]) == 'object');
  var e = (i) ? arguments[0] : window;
  var p = (i) ? arguments[1] : arguments[0];
  var h = (i) ? arguments[2] : arguments[1];
  if ((p) && (h)) {
    var old = e[p];
    if (old) {
      e[p] = function () {
               var res = old();
               res = h(res);
               if (res != undefined) {
                 return res;
               }
             };
    } else {
      e[p] = h;
    }
  }
}

//
window.onbeforeunload = deactivate;
window.onerror = function (name, desc, number) {alert(name + " - " + desc + " - " + number); return false;};
