/* Global objects */
var oBrowser = new Browser();

var CX = {

  submitOnEnter : null, // Contains script for submitting forms
  modified : false,     // Indicates wether a form element was modified
  checkUrl : null,
  uncheckUrl : null,
  dialogWindow : null,
  language : null,
  loadedScript : [],
  approve : false,
  selftest: false,

  initialize : function() {
    // Get language from meta tag info
    var metatags = document.getElementsByTagName("meta");
    for (i= 0; i < metatags.length; i++) {
      if (metatags[i].getAttribute("name") == "language") {
        this.language = metatags[i].getAttribute("content");
        break;
      }
    }
    document.on('dom:loaded', function() { CX.tooltip.init($(document.body)) } );
  },
  
  getChangedElementsConditionally : function (url, formName, formElements) {
    var nrOfValues = 0;
    formElements.each(function(formElement) {
      if (formElement.getValue() != "") {
        nrOfValues++;
      }
    });
    if (nrOfValues == 0 || nrOfValues == formElements.size()) {
      CX.getChangedElements(url, formName);
    }
  },

  getChangedElements : function (url, formName) {
    document.body.style.cursor = 'wait';
    var params = {};
    if (formName) {
        var submitForm = document.forms[formName];
        params = $(submitForm).serialize(true);
    }
    params.ajax = true;
    params.currenttime = new Date().getTime();    
    params.jsCall = "CX.getChangedElements('" + url + "'";
    if (this.selftest) {
        if (formName) {
          params.jsCall +=  ",'" + formName + "')";
        } else {
          params.jsCall += ")";
        }
    }
    if (this.approve) {
        params.Approve = "Approve";
        this.approve = false;
    }
    new Ajax.Request(url, {method: 'post', parameters: params, onSuccess: function(transport) {
        var xAjaxString = transport.responseText;
        if (xAjaxString != '') {
            if (xAjaxString == "RELOAD:/engine") {
              location.href = "/engine";
            } else if (xAjaxString == "EXPIRED") {
      		  location.href = "/engine";  
            } else if (xAjaxString.isJSON()) {
              var xAjaxObject = xAjaxString.evalJSON();
              var action = xAjaxObject["action"];
              var elementList = xAjaxObject["elements"];
              var popup = xAjaxObject["popup"];
              var js = xAjaxObject["js"];
              if (elementList) {
                for (var i = 0; i < elementList.length; i++) {
                  var elementPair = elementList[i];
                  var element = $(elementPair[0]);
                  var newHTML = elementPair[1];
                  if (element) {
                    switch(action) {
                      case "replace":
                        element.replace(newHTML);
                        if (newHTML != '') {
                          // The replaced element always has the same id.
                          var freshElement = elementPair[0];
                          CX.tooltip.init($(freshElement));
                        }
                        break;
                      case "before":
                        element.insert({"before":newHTML});
                        break;
                      case "after":
                        element.insert({"after":newHTML});
                        break;
                      case "remove":
                        element.remove();
                        break;
                      case "update":
                        element.update(newHTML);
                        CX.tooltip.init(element);
                        break;
                    }
                  } else {
                    CX.sendNotification('AJAX-ERROR: HTML element ' + elementPair[0] + ' not found in DOM.');
                  }
                }
              }
              if (popup) {
                CX.dialogWindow = CX.openPopupBox("popup","Message", 400, 150, "cx_popup", null);
                var ok = "CX.closeDialog()";
                var html = popup + "<div align=\"center\"><form name=\"cx_dialogForm\"><input id=\"cx_dialog-yes\" type=\"button\" name=\"OK\" value=\"OK\" onclick=\"" + ok + "\"></form></div>";
                CX.dialogWindow.getContent().innerHTML = html;
              }
              eval(js);
            } else {
                CX.sendNotification('AJAX-ERROR: Response for request "' + url + '" was not valid JSON', xAjaxString);
                location.href = "/engine";
            }
        } else {
            /* 
             * Dit hoeft niet erg te zijn. Er kan een calculated veld zijn dat wel van waarde
             * verandert door een autosubmit maar niet in het scherm staat. Dus geen html. Dus geen 
             * notifier.
             * 
             * CX.sendNotification('AJAX-ERROR: Application engine returned an empty string');
             */ 
        }
        document.body.style.cursor = 'default';
      }
    });   
  },

  // velocity
  updateDOM : function(element, url, form) {
    var parameters = {};
    if (form) {
      parameters = $(form).serialize(true);
    }
    new Ajax.Request(url, {method: 'post', parameters: parameters, onSuccess: 
      function(transport) {
        $(element).replace(transport.responseText);
      }}
    );
  },

  sendNotification : function(message, body) {
    var params = {};
    params.service = "engine";
    params.cmd = "notify";
    params.message = message;
    params.body = body;
    params.ajax = 'true';
    new Ajax.Request("/engine", {method:'post',parameters:params});
  },


  sendStayAlive : function () {
    var url = '/engine?service=session&cmd=stayalive';
    new Ajax.Request(url);
  },

  startStayAlive : function (seconds) {
    var interval = seconds * 1000;
    setInterval('CX.sendStayAlive()', interval);
  },

  addHtmlEditor : function(identifier) {
    var button = $(identifier + "_editorbutton");
      if (!tinyMCE.get(identifier)) {
        tinyMCE.execCommand('mceAddControl', true, identifier);
        $(identifier).setAttribute("editor","true");
        button.setAttribute("title",button.getAttribute("titleOn"));
    } else {
        tinyMCE.execCommand('mceRemoveControl', true, identifier);
        $(identifier).removeAttribute("editor");    
        button.setAttribute("title",button.getAttribute("titleOff"));
    }
  },

  countCharMCE : function(editor, maxLength, msg) {
    var editorId = editor.id;
    var txt = tinyMCE.get(editorId).getContent();
    var p = tinymce.DOM.get(editorId + '_path_row');
    var txtLength = txt.length;
    var countMsg = txtLength;
    if (txtLength > maxLength) {
      countMsg += " " + msg;
    }
    tinymce.DOM.setHTML(p, countMsg);
  },

  processCtrlQ : function (event) {
    var keyCode;
    var ctrlKeyPressed=false;
    if (oBrowser.isNS) {
      keyCode = event.which;
      if (event.ctrlKey) {
        ctrlKeyPressed=true;
      }
    } else {
      keyCode = window.event.keyCode;
    }
    if (keyCode == "17" || (keyCode == "113" && ctrlKeyPressed)) { // 17 IE 113 Firefox etall.
      top.location = "/engine?service=mainmenu";
    }
    return keyCode;
  },

  // Expects pathnames of the required (java)scripts
  loadScript : function () {
    for (var i = 0; i < arguments.length; i++) {
      var path = arguments[i];
      var script = new Element("script", { type: "text/javascript", src: arguments[i] });
      $$("head")[0].insert(script);
    }
  },
 
  // Wat als er meer dan 1 op het scherm is?
  newDoubleSelectBox : function (boxId, formName) {
    if (this.loadedScript.indexOf("doubleselectbox") == -1) {
      document.observe("doubleselectbox:loaded", function() { CX.loadedScript.push("doubleselectbox");CX.newDoubleSelectBox(boxId, formName) });
      this.loadScript("/engine/optiontransfer/OptionTransfer.js","/engine/optiontransfer/selectbox.js");
    } else {
      var doubleSelectBox = new OptionTransfer(boxId + "_left", boxId + "_right", boxId);
      doubleSelectBox.setAutoSort(false);
      doubleSelectBox.setDelimiter(",");
      doubleSelectBox.saveNewRightOptions(boxId);
      $(boxId + "_transferRight").onclick = function() { doubleSelectBox.transferRight(); if (formName != "") { $(formName).submit();} }
      $(boxId + "_transferAllRight").onclick = function() { doubleSelectBox.transferAllRight(); if (formName != "") { $(formName).submit();} }
      $(boxId + "_transferLeft").onclick = function() { doubleSelectBox.transferLeft(); if (formName != "") { $(formName).submit();} }
      $(boxId + "_transferAllLeft").onclick = function() { doubleSelectBox.transferAllLeft(); if (formName != "") { $(formName).submit();} }
      $(boxId + "_moveUp").onclick = function() { doubleSelectBox.moveUp() }
      $(boxId + "_moveDown").onclick = function() { doubleSelectBox.moveDown() }
      $(boxId + "_right").ondblclick = function() { doubleSelectBox.transferLeft(); if (formName != "") { $(formName).submit();} }
      $(boxId + "_left").ondblclick = function() { doubleSelectBox.transferRight(); if (formName != "") { $(formName).submit();} }
      doubleSelectBox.init($(boxId).form);
    }
  },

  checklist: function(elementName) {
    var checklist = this;
    this.elementName = elementName;
    this.element = $('cx_checklist-' + elementName);
    this.container = $('cx_checklistcontainer-' + elementName);
    this.dropdown = $('cx_checklistdropdown-' + elementName);
    this.show = function() {
      var element = checklist.element;
      element.show();
      element.activeArea = true;
      Event.observe(document, 'click', function() { checklist.hide() });
      element.observe('mouseover',function() { element.activeArea = true; });
      element.observe('mouseout',function() { element.activeArea = false; });
      checklist.container.observe('mouseout',function() { element.activeArea = false; });
    };
    this.hide =  function () {
      var element = checklist.element;
      if(!element.activeArea) {
        element.hide();
        Event.stopObserving(document, 'click', function() { checklist.hide(); });        
        var checkboxes = element.select('input');
        var labels = element.select('label');
        var checked = "";
        for (var i = 0; i < checkboxes.size(); i++) {
          var checkbox = checkboxes[i];
          if (checkbox.checked) {
            var value = labels[i].innerHTML;
            if (checked == "") {
              checked += value;
            } else {
              checked += ", " + value;      
            }
          }
        }
        checklist.dropdown.update(checked);
      }
    };
    this.container.observe('click', checklist.show);
  },

  selectAll : function (checkbox, tableIdentifier) {
    if (checkbox.checked) {
      new Ajax.Request(checkbox.getAttribute("checkAllUrl"));
    } else {
      new Ajax.Request(checkbox.getAttribute("unCheckAllUrl"));
    }
    this.selectPage(checkbox, tableIdentifier);
  },

  selectPage : function (checkbox, tableIdentifier) {
    var checkboxes = $(tableIdentifier).select('.cx_check');
    checkboxes.each(function(box) {
      box.checked = checkbox.checked;
    });
  },

  /* Captures Enter Key when needed */
  setEnterEventHandler : function() {
    var length = document.forms.length;
    for (var i = 0; i < length; i++) {
      var f = document.forms[i];
      // Hack for workbench. May be removed when all forms can be adressed by name.
      if(f.name != 'searchDocs') {
        var el = f.elements;
        var length1 = el.length;
        for (var j = 0 ; j < length1 ; j++) {
          var element = f.elements[j];
          if (element.type == "text" || element.type=="password" || element.type=="checkbox") {
            element.onkeydown = this.keyDown;
          }
        }
      }
    }
    if (oBrowser.isNS) {
      document.captureEvents(Event.KEYDOWN|Event.KEYUP);
    }
  },

  keyDown : function (event) {
    var keyCode = getKeyCode(event);
    if (keyCode == 13) { // enter key pressed
      eval(CX.submitOnEnter);
      return false; // don't pass enter to the screen
    } else { // pass the other keys to the screen
      return true;
    }
  },

  setFocus : function (elementName) {
    var elementObject = $(elementName);
    if (elementObject != null) {
      if (elementObject.style.display == 'none') {
        // The html editor hides the original textarea and uses an iframe to display its content.
        // The focus cannot be set to the textarea, only to the iframe.
        var htmlEditor = elementObject.ancestors().first().getElementsBySelector('iframe').first();
        if(htmlEditor != undefined) { htmlEditor.contentWindow.focus(); }
      } else if (elementObject.disabled == false) {
        elementObject.focus();
      }
    } else {
      // Hack for workbench. May be removed when all forms can be adressed by name.
      if (document.forms[0] && document.forms[0].name != "searchDocs") {
        for (var i = 0; i < document.forms[0].length; i++) {
          elementObject = document.forms[0].elements[i];
          if (elementObject.type == "text" ||elementObject.type== "radio" ||elementObject.type== "checkbox") {
            /* If the element is disabled we skip focus because otherwise the page might scroll up */
            if (elementObject.disabled == false) {
              elementObject.focus();
            }
            break;
          }
        }
      }
    }
  },

  setAsModified : function() {
    this.modified = true; 
    $$('.cx_button-save').each(function(element) {
      element.className += " modified";
    }) 
  },
  
  getSubmitScript : function (formName, actionUrl) {
    var rv = "document.forms['" + formName + "'].action = '" + actionUrl + "';";
    rv += "document.forms['" + formName + "'].target = '_self';";
    rv += "document.forms['" + formName + "'].submit();";
    return rv;
  },
  
  openDialogForSave : function (element, url, clazzId, dialogText) {
    if (this.modified != true) {
      return true;
    }
    // Guard against opening more then one dialog.
    if (CX.dialogWindow != undefined) {
      return false;
    }
    // For now it is assumed the element is on the form.
    var ancestors = $(element).ancestors();
    var formName = null;
    ancestors.each(function(ancestor) {
      if (ancestor.nodeName == "FORM") {
        formName = ancestor.name;
      }
    });
    var parameter = "dosave=" + clazzId; 
    if(url.indexOf("?") == -1) {
      parameter = "?" + parameter;
    } else {
      parameter = "&" + parameter;
    }
    var dialogTitle = dialogText.title;
    var dialogContent = dialogText.message;
    var labelyes = dialogText.yes;
    var labelno = dialogText.no;
    var labelcancel = dialogText.cancel;
    var yes = CX.getSubmitScript(formName, url + parameter);
    var no = "location.href = '" + url + "'";
    var cancel = "CX.closeDialog()";
    CX.dialogWindow = new Window({
      className: "cx_popup", 
      title : dialogTitle,
      width: 350, 
      height: 100,
      zIndex: 100, 
      minimizable: false,
      maximizable: false,
      resizable: false, 
      draggable: true,
      closable: false,
      destroyOnClose: true,
      onShow: function() { $('cx_dialog-yes').focus() }
    });
    CX.dialogWindow.getContent().innerHTML = "<div style=\"padding:10px;font-size:12px;color:black;text-align:center\">" + dialogContent + 
      "<br><br>" +
      "<form name=\"cx_dialogForm\">" +
      "<input id=\"cx_dialog-yes\" type=\"button\" name=\"yes\" value=\"" + labelyes +"\" onclick=\"" + yes + "\">&nbsp;" +
      "<input type=\"button\" name=\"no\" value=\"" + labelno + "\" onclick=\"" + no + "\">&nbsp;" +
      "<input type=\"button\" name=\"cancel\" value=\"" + labelcancel + "\" onclick=\"" + cancel + "\">" +
      "</form>" + 
      "</div>"; 
    CX.dialogWindow.showCenter(true);
    return false;
  },
  
  closeDialog : function() {
    CX.dialogWindow.close();
    CX.dialogWindow = null;
  },

  openPopupBox : function (xid, xtitle, xwidth, xheight, theme, pageURL) {
    var win = new Window({
      className: theme, 
      title: xtitle, 
      width: xwidth, 
      height: xheight, 
      id: xid, 
      url: pageURL, 
      resizable: true, 
      closable: true, 
      showEffectOptions: {duration:1.5}, 
      destroyOnClose: true, 
      recenterAuto: false,
      zIndex: 1000
    });
    win.showCenter(true);
    return win;
  },

  closePopupBox : function closePopupBox () {
    Windows.getFocusedWindow().close();
  },

  dragBar : function() { dragBar.initialize(); },

  /* Mag wel wat netter */
  toggleParagraph : function (elemId,imgElemId,iconOff,iconOn, url) {
    elem = $(elemId);
    imgElem = $(imgElemId);
    if (elem.style.display == 'block'){
      elem.style.display = 'none';
      imgElem.src = iconOn;
    } else {
      elem.style.display = 'block';
      imgElem.src = iconOff;
    }
    new Ajax.Request(url)
  },

  openSelfTestConsole : function () {
    var windowName = 'selftest_' + document.domain.replace(/\./g,'_');
    window.open('/engine?service=selftest&cmd=getconsole',windowName,'height=220,width=1000,scrollbars=yes,resizable=yes');
  },

  openUrlInOpener : function (url) {
    opener.location.href = url;
  },

  tooltip : {
    init : function(container) {
      Tips.hideAll();
      container.select('[data-tooltip]').each(function(element) { 
        new Tip(element, element.getAttribute("data-tooltip"), {
          style: 'default',
          stem: 'topLeft',
          border: 3,
          radius: 3,
          hook: false,
          offset: { x:16, y: 8 },
          delay: 0.25,
          hideAfter: 3,
          hideOthers: true,
          viewport: true
        });
        element.title = "";
      });
    }
  },

  calendar : {
    url : null,
    params : null,
    onCalendar : false,
    shim : null,
    set : function(identifier, dateParts) {
      var formElement;
      for (part in dateParts) {
        formElement = $(part);
        formElement.value = dateParts[part];
      };
      this.onCalendar = false;
      this.hide(identifier);
      if (formElement.onchange) {
        formElement.onchange();
      }
    },
    show : function(identifier) {
      var url = CX.calendar.url;
      if (url.indexOf('?') == -1) {
        url += "?identifier=" + identifier;
      } else {
        url += "&identifier=" + identifier;
      }
      var dayIdentifier = $(identifier + ':d');
      var monthIdentifier = $(identifier + ':M');
      var yearIdentifier = $(identifier + ':y');
      if (dayIdentifier != null && monthIdentifier != null && yearIdentifier != null) {
        var day = dayIdentifier.value;
        var month = monthIdentifier.value;
        var year = yearIdentifier.value;
      } else {
        url += "&datatype=string"
      }
      if (year != "null" && month != "null" && day != "null") {        
        var iDay = parseInt(day);
        var iMonth = parseInt(month);
        if (iDay < 10) { day = "0" + iDay; }
        if (iMonth < 10) { month = "0" + iMonth; }
        var selectedDate = year + month + day;
        url += "&" + identifier + "=" + selectedDate;
      }      
      if (CX.calendar.params != null) {
        for (var key in CX.calendar.params) {
          url += "&" + key + "=" + CX.calendar.params[key];
        }
      }
      CX.eventRef = function() { CX.calendar.hide(identifier) };
      Event.observe(document,'click', CX.eventRef);
      CX.getChangedElements(url);
    },
    hide : function(identifier) {
      var calendar = $('cx_calendar-' + identifier);
      if (calendar && !CX.calendar.onCalendar) {
        if (CX.calendar.shim != null) {
          $(CX.calendar.shim).remove();
          CX.calendar.shim = null;
        }
        calendar.hide();
        Event.stopObserving(document,'click', CX.eventRef);
      }
    },
    clear : function(container) {
      var selectors = $(container).getElementsBySelector('select');
      var inputs = $(container).getElementsBySelector('input');
      var formElement;
      selectors.each(function(e) { formElement = e; e.clear(); });
      inputs.each(function(e) { formElement = e; e.clear(); });
      if (formElement.onchange) {
        formElement.onchange();
      }
    },
    createShim : function(identifier) { 
      if (!window.XMLHttpRequest) CX.calendar.shim = CX.useShim('cx_calendar-' + identifier);
    }
  },

  // IE6 needs an iframe, the 'shimframe', to cover dropdown list elements
  useShim : function(identifier) {
   var element = $(identifier);
   var shim = document.createElement('iframe');
   shim.setAttribute('src','about:blank');
   element.setAttribute('myshim',shim);
   shim.style.width = element.clientWidth + 2;
   shim.style.height = element.clientHeight + 2;
   element.parentNode.appendChild(shim);
   return shim;
  },
  
  setValueFromPopup : function(identifier, value, valueLabel) {     
    var inputElement = parent.$('cx_searchboxinput-' + identifier);
    if (inputElement) {
        inputElement.value = value;
        var urlElement = parent.$('cx_searchbox-' + identifier);
        urlElement.innerHTML = valueLabel;
        //call onchange event to trigger possible autosubmit
        inputElement.onchange();
    } else {
        alert('No input element on form for value setter.');
    }
    parent.CX.closePopupBox();
  },

  createTableDragHandler : function(tbodyId, tableKey) {
    var handler = {
      tbody: $(tbodyId),
      xKey: tableKey,
      rows: null,
      draggedRow: null,
     
      init: function() {
        this.rows = $$('#' + this.tbody.id + ' tr.cx_row'); 
      },
      drop: function(object) {
        if (object == this.tbody) {
          var from = this.getOriginalRowNr();
          var to = this.getCurrentRowNr();
          CX.getChangedElements("/engine?service=table&cmd=dragrow&x-key=" + this.xKey + "&from=" + from + "&to=" + to);
        }
        this.draggedRow = null;
        this.init();
      },
      change: function(object) {
        if (!this.draggedRow) {
          this.draggedRow = object;
        }
      },     
      getOriginalRowNr: function() {
        for (var i = 0; i < this.rows.length; i++) {
           if (this.rows[i] == this.draggedRow) {
             return i;
           }
        }
        return null;
      },
      getCurrentRowNr: function() {
        var currentRows = $$('#' + this.tbody.id + ' tr.cx_row');
        for (var i = 0; i < currentRows.length; i++) {
          if (currentRows[i] == this.draggedRow) {
            return i;
          }
        }
        return null;
      }
    }
    handler.init();
    Sortable.create(tbodyId, {tag: "tr", handle: "img.cx_dragicon", onUpdate: function(object) { handler.drop(object); }, onChange: function(object) { handler.change(object); }})
    return handler;
  }
}

CX.initialize();

/* Document event handlers */
// Alt-mousedown returns to engine panels
document.onmousedown = function(e) {
 var altPressed = 0;
 var evt = navigator.appName=="Netscape" ? e:event;
 altPressed = evt.altKey;
 if (altPressed) top.location = "/engine?service=mainmenu";
  return true;
 };
// We keep Ctrl-Q to return to engine panels for Netscape browsers
document.onkeypress = CX.processCtrlQ;
// Backward compatibility
function setCtrlQEventHandler() {
 document.onkeypress = CX.processCtrlQ;
}

// Used by colorpicker
String.prototype.toCSSColor = function () {
  var rv;
  var re = /^([0-9a-f]{3}$|^[0-9a-f]{6})$/i;
  var valid = this.match(re);
  valid == null ? rv = this: rv = "#" + this;
  return rv;
}

// Not the same as viewport in prototype and we need this sometimes. Perhaps superfluous.
window.getDimensions = function() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return {'width':myWidth,'height':myHeight};
}

dragBar = {
  leftpaneXpos : 0,
  initialize : function() {
    if ($('cx_dragline')) {
      Event.observe($('cx_dragline'), 'mousedown', dragBar.position);
      this.leftpaneXpos = Position.page($('cx_leftpane'))[0];
    }
  },
  position : function(event) {
    Event.observe(document,'mousemove',dragBar.newPosition);
    Event.observe(document, 'mouseup', dragBar.aktion);
    return false;
  },
  aktion : function(event) {
    Event.stopObserving(document,'mousemove',dragBar.newPosition);
    Event.stopObserving(document, 'mouseup', dragBar.aktion);
    var url = '/engine?service=session&cmd=setpanewidth&size=' + $('cx_leftpane').getWidth();
    new Ajax.Request(url);
    return false;
  },
  newPosition : function(event) {
    var mousepos = Event.pointerX(event);
    var newWidth = mousepos - dragBar.leftpaneXpos;
    if (newWidth < 1) newWidth = 1;
    $('cx_leftpane').style.width = newWidth + 'px';
  }
}

/* This general function captures various keys the user may press. */
function getKeyCode(events) {
  if (oBrowser.isNS) {
    return events.which;
  } else {
    return window.event.keyCode;
  }
}

/* Could be part of a form-extension */
function focusNext(formField, nextField) {
  if (formField.value.length == formField.getAttribute('maxLength')) {
    $(nextField).focus();
  }
}

/* Remove or form-extension? */
function setLookupList(aLookupList, element) {
  if (element.type == "select-one") {
    selector = element;
    for (var i=0; i < selector.options.length; i++) {
      selector.options[i] = null;
    }
    selector.options.length = 0;
    selector.options[0] = new Option('---','',false)
    for (var i=1; i < aLookupList.length; i++) {
      selector.options[selector.length] = new Option(aLookupList[i][1],aLookupList[i][0]);
    }
  }
}

/* Browser detection object. In general is is better to handle cross-browser tests at the
 * object or method level instead of relying on the navigator information.
 */
function Browser() {
  var ua, s, i;
  this.isIE    = false;
  this.isNS    = false;
  this.isSafari = false;
  this.version = null;

  ua = navigator.userAgent;
  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
    s = "Safari";
      if ((i = ua.indexOf(s)) >= 0) {
    this.isSafari = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
  // Treat "Gecko" browser as NS 6.1.
  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}


/* The End */
