/* 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,

  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;
      }
    }
  },

  addHtml : function(identifier, url, how, formName) {
    var marker = $(identifier);
    if (marker) {
      var currentTime = new Date();
      url.indexOf("?") == -1 ? url += "?" : url += "&";
      url += "ajax=true&currenttime=" + currentTime.getTime();
      var params = {};
      if (formName) {
      	var submitForm = document.forms[formName];	
      	params = $(submitForm).serialize(true);
      }
      switch(how) {
      	case "remove":
          new Ajax.Request(url, {onSuccess: function(transport) { if (transport.responseText == "OK") { marker.remove(); } else { location.href = "/engine"; }}});
          break;      	 
      	case "before":
          new Ajax.Updater(marker,url, {insertion:Insertion.Before,method:'post',parameters:params});
          break;
        case "after":
          new Ajax.Updater(marker,url, {insertion:Insertion.After,method:'post',parameters:params});
          break;
        case "replace":
          new Ajax.Request(url, {method:'post',parameters:params,onSuccess: function(transport) {
            var html = transport.responseText;
          	if (html.indexOf("<html>") == -1) {
          	  marker.replace(html);
          	} else {
          	  CX.sendNotification('AJAX-ERROR: Application engine did not return a html fragment');
          	}
          }});
          break;
        case "innerreplace":
          new Ajax.Updater(marker,url, {method:'post',parameters:params});
          break;
      }
    } else {
      this.sendNotification('AJAX-ERROR: Marker element ' + marker + 'not found in DOM tree');
      location.href = "/engine";
    }
  },

  addHtmlBefore : function(identifier, url) {
  	this.addHtml(identifier, url, "before");
  },

  addHtmlAfter : function(identifier, url) {
  	this.addHtml(identifier, url, "after");
  },

  addHtmlReplace : function(identifier, url) {
  	this.addHtml(identifier, url, "replace");
  },

  addHtmlInnerReplace : function(identifier, url) {
  	this.addHtml(identifier, url, "innerreplace");
  },

  addHtmlEditor : function(identifier) {
    var memo = $(identifier);
	var button = $(identifier + "_editorbutton");
    if (memo.getAttribute("editor") == null) {
  		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);
  },
  
  sendNotification : function(message) {
  	var url = '/engine?service=engine&cmd=notify&message=' + message;
  	new Ajax.Request(url);
  },

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

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

  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.
      location = "/engine?service=mainmenu";
    }
    return keyCode;
  },

  newDoubleSelectBox : function (boxId, formName) {
  	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);
  },

  selectAll : function (checkbox) {
    if (checkbox.checked) {
      new Ajax.Request(this.checkUrl);
    } else {
  	  new Ajax.Request(this.uncheckUrl);
    }
    this.selectPage(checkbox);
  },

  selectPage : function (checkbox) {
    var eList = checkbox.form.elements;
    for (var i=0; i < eList.length ; i++) {
      if (eList[i].type == "checkbox" && eList[i].name != "action:checkall") eList[i].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;
  },

  // TODO: Remove???
  onsubmit : function (form) {
    if (form.onsubmit) {
      form.onsubmit();
    }
  },
  
  openDialogForSave : function (element, url, clazzId, msg) {
  	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 yes = CX.getSubmitScript(formName, url + parameter);
    var no = "location.href = '" + url + "'";
    var cancel = "CX.closeDialogForSave()";
    CX.dialogWindow = new Window({
      className: "cx_popup", 
      title : "Save changes?",
      width: 350, 
      height: 100,
      zIndex: 100, 
      minimizable: false,
      maximizable: false,
      resizable: false, 
      draggable: true,
      closable: false,
      destroyOnClose: true,
      onShow: function() { $('cx_dialog-yes').focus() }
    });
    if (CX.language == "en") {
    	var labelyes = "Save";
    	var labelno = "Don't save";
    	var labelcancel = "Cancel";
    } else {
    	var labelyes = "Bewaren";
    	var labelno = "Niet bewaren";
    	var labelcancel = "Annuleren";
    }
    CX.dialogWindow.getContent().innerHTML= "<div style=\"padding:10px;font-size:12px;color:black;text-align:center\">" + msg + 
      "<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;
  },
  
  closeDialogForSave : 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);
  },

  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;
  },

  calendar : {
  	url : null,
  	params : null,
  	onCalendar : false,
  	shim : null,
    show : function(identifier) {
      var url = CX.calendar.url + "&identifier=" + identifier;
      var day = $(identifier + ':d').value;
      var month = $(identifier + ':M').value;
      var year = $(identifier + ':y').value;
      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];
	    }
      }
      url += "&ajax=true";
      CX.eventRef = function() { CX.calendar.hide(identifier) };
      Event.observe(document,'click', CX.eventRef);
      new Ajax.Updater(identifier + '_container',url, { onException: function() { this.sendNotification('AJAX-ERROR: Calendar problem') }, onComplete: function() { if (!window.XMLHttpRequest) CX.calendar.shim = CX.useShim('cx_calendar-' + identifier)}});
    },
    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);
      }
    }
  },

  // 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 = top.$('cx_searchboxinput-' + identifier);
  	inputElement.value = value;
  	var urlElement = top.$('cx_searchbox-' + identifier);
  	urlElement.innerHTML = valueLabel;
  	top.CX.closePopupBox();
  }
}

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) 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;
}

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;
}

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();
  }
}

/* Still in engine but not in use 09-2007 */
function treeAction(url) {
  this.window.location = url;
}

// TODO: Change to generic call to handle field calculations/validations/actions then move to CX context.
function getStreetCity(url, zipField, numberField, streetField, cityField) {
  // Check if targetfields for calculation exist
  if($(streetField) || $(cityField)) {
    zip = $(zipField).value;
    nr = $(numberField).value;
    url = url + '&zip=' + zip + '&number=' + nr + '&streetfield=' + streetField + '&cityfield=' + cityField;
    new Ajax.Request(url, { onSuccess: function(transport) { setFormElements(transport.responseText) }} );
  } else {
  	return false;
  }
}

function setFormElements(response) {
  var oStreetCity = response.evalJSON();
  for (var i in oStreetCity) {
  	var newValue = oStreetCity[i];
  	if (newValue != "") {
  		$(i).value = oStreetCity[i];
  	}
  }
}

/* TODO Form extension, part of prototype? */
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 */
