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

var CX = {
      
  language : null,

  submitOnEnter : null, // Contains script for submitting forms
   
  modified : false,   // Indicates wether a form element was modified

  checkUrl : null,

  uncheckUrl : 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) {
    var marker = $(identifier);
    if (marker) {
      var currentTime = new Date();
      // We gaan 'r n vanuit dat er altijd al een querystring is...
      url = url + "&ajax=true&currenttime=" + currentTime.getTime();
      switch(how) {
      	case "before":
          new Ajax.Updater(marker,url, {insertion:Insertion.Before,method:'get'});
          break;
        case "after":
          new Ajax.Updater(marker,url, {insertion:Insertion.After,method:'get'});
          break;
        case "replace":
          new Ajax.Request(url, {onSuccess: function(transport) { 
          	                                  var html = transport.responseText;
          	                                  if (html.indexOf("<html>") == -1) {
          	                                    marker.replace(html);
          	                                  } else {
          	                                  	alert('error!');
          	                                  }
          	                                }
          	                     });
          break;
        case "innerreplace":
          new Ajax.Updater(marker,url, {method:'get'});
          break;
      }
    } else {
      this.sendNotification('AJAX-ERROR: Marker element 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");
  },
 
  
  sendNotification : function(message) {
  	var url = '/engine?service=engine&cmd=notify&message=' + message;
  	new Ajax.Request(url);
  },

  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) {
  	var doubleSelectBox = new OptionTransfer(boxId + "_left", boxId + "_right", boxId);
  	doubleSelectBox.setAutoSort(false);
  	doubleSelectBox.setDelimiter(",");
  	doubleSelectBox.saveNewRightOptions(boxId);
    $(boxId + "_transferRight").onclick = function() { doubleSelectBox.transferRight() }
    $(boxId + "_transferAllRight").onclick = function() { doubleSelectBox.transferAllRight() }
    $(boxId + "_transferLeft").onclick = function() { doubleSelectBox.transferLeft() }
    $(boxId + "_transferAllLeft").onclick = function() { doubleSelectBox.transferAllLeft() }
    $(boxId + "_moveUp").onclick = function() { doubleSelectBox.moveUp() }
    $(boxId + "_moveDown").onclick = function() { doubleSelectBox.moveDown() }
	$(boxId + "_right").ondblclick = function() { doubleSelectBox.transferLeft() }
	$(boxId + "_left").ondblclick = function() { doubleSelectBox.transferRight() }  	
  	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;
    }
  },

  discardChanges : function (msg) {
    if (this.modified == true) {
      return confirm(msg);
    } else {
      return true;
    }
  },

  /* 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; if($('cx_button-save')) $('cx_button-save').className += " modified"; 
  },

  onsubmit : function (form) {
    if (form.onsubmit) {
      form.onsubmit();
    }
  },

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

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

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

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

dragBar = {
  leftpaneXpos : 0,
  initialize : function() {
    if ($('cx_dragline')) {
      Event.observe($('cx_dragline'), 'mousedown', dragBar.position);
      Event.observe(document, 'mouseup', dragBar.aktion);
      this.leftpaneXpos = Position.page($('cx_leftpane'))[0];
    }
  },  
  position : function(event) {
    Event.observe(document,'mousemove',dragBar.newPosition);
    return false;
  },
  aktion : function(event) {
    Event.stopObserving(document,'mousemove',dragBar.newPosition);
    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]);
    }
  }
}

/* TODO replace with prototype? */
function getElementsByClassName(oElm, strTagName, strClassName){
  var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
  var arrReturnElements = new Array();
  strClassName = strClassName.replace(/\-/g, "\\-");
  var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
  var oElement;
  for (var i=0; i<arrElements.length; i++){
    oElement = arrElements[i];
    if (oRegExp.test(oElement.className)){
      arrReturnElements.push(oElement);
    }
  }
  return (arrReturnElements)
}

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