var isFirefox = navigator.product == "Gecko";

var ctsWebsite;
var popup;
var popupLoader;
var popupIsLoading = false;
var POPUP_HEIGHT_ADD_IE = 0;
var POPUP_HEIGHT_ADD_FF = 12;
var USE_IE_MODAL_DIALOG = true;
var csHelperIFrames = new Array();

var ALL_JAVASCRIPT_ERRORS = new Array();

var modalResult;
if (isFirefox) {
  var modalCommand;
  var modalDialog;
}

function registerEvent(component, name, functionName) {
  if (component.addEventListener) {
    component.addEventListener(name, functionName, true);
  } else if (component.attachEvent) {
    component.attachEvent("on" + name, functionName);
  }
}

function denyFunction(evt) {
  if (isFirefox) {
  	evt.preventDefault();
		evt.stopPropagation();
  } else {
    window.event.returnValue=false;
  }
  return false;
}
function executeModalDialog(url, target, style, command, dontUseIE) {
  if (!target || target != "") target = "_blank";
  if (isFirefox || dontUseIE || !USE_IE_MODAL_DIALOG) {
    modalCommand = command;
    modalResult = null;
    style = "dependent=yes,modal=yes,dialog=yes,"+style;
    style = style.replace("dialogWidth","width").replace("dialogHeight", "height").replace(/[;]/gi,",").replace(/[:]/gi,"=").replace(/,$/, "");
    modalDialog = window.open(url, target, style);
    window.setTimeout("evaluateModal()", 100);
  } else {
    modalResult = showModalDialog(url,target, style);
    evaluateModalResult(modalResult, command);
  }
}

function evaluateModal() {
  if (modalDialog) {
    try {
      var isClosed = modalDialog.closed;
    } catch (e) {
      var isClosed = true;
    }
    if (isClosed) {
      evaluateModalResult(modalResult, modalCommand);
    } else {
      window.setTimeout("evaluateModal()", 100);
    }
  }
}

function evaluateModalResult(modalResult, command) {
  if (modalResult && modalResult != null && modalResult != undefined && modalResult != 'CANCEL') {
    var EVAL_JS_PREFIX = "CS:EVAL_JAVASCRIPT=";
    if (modalResult.indexOf && modalResult.indexOf(EVAL_JS_PREFIX) == 0) {
      eval(modalResult.substring(EVAL_JS_PREFIX.length));
    } else {
      eval(command);
    }
  }
}

function getAttributeString(obj) {
  var outer = outerHTML(obj);
  var startIndex = outer.toLowerCase().indexOf("<"+obj.tagName.toLowerCase());
  if (startIndex == -1) return "";
  var endIndex = outer.indexOf(">", startIndex);
  startIndex = outer.indexOf(" ", startIndex);
  if (startIndex >= endIndex || startIndex == -1) return "";
  return outer.substring(startIndex, endIndex);
  /**
  var attributes = "";
  var atts = obj.attributes;
  for(var i = 0; i < atts.length; i++) {
    if (atts[i].value != "") attributes += " "+atts[i].name + "=\"" + atts[i].value+"\"";
  }
  return attributes;
  */
}

function outerHTML(obj) {
  if (isFirefox) {
    var clone = obj.cloneNode(true);
    var span = obj.ownerDocument.createElement("span");
    span.appendChild(clone);
    return span.innerHTML;
  } else {
    return obj.outerHTML;
  }
}

function innerText(obj) {
  if (!obj.innerHTML || obj.innerHTML.length ==0) return "";
  var doc = isFirefox ? obj.ownerDocument : obj.document;
  var newChar = doc.createTextNode(".");  
  obj.appendChild(newChar);  // to count ending spaces
  var innerText = isFirefox ? stripHTML(obj.innerHTML) : obj.innerText;
  obj.removeChild(newChar);
  innerText = trim(innerText);
  innerText = innerText.substring(0, innerText.length-1);
  return innerText;
}

function stripHTML(html) {
  var div = document.createElement('div');
  div.style.display = "none";
  div.innerHTML = html;
  document.body.appendChild(div);
  var rng = document.createRange();
  rng.selectNode(div);
  var text =  rng.toString();
  document.body.removeChild(div);
  return text;
}

function trim(sToTrim, trimInnerText) {
  	//replace carriage returns and line feeds
  sToTrim = sToTrim.replace(/[\r]/g,"");
  sToTrim = sToTrim.replace(/^\s+/g,"");
  sToTrim = sToTrim.replace(/\s+$/g,"");
  if (trimInnerText) {
    sToTrim = sToTrim.replace(/[\n]+/g," ");
    sToTrim = sToTrim.replace(/[ ]+/g, " ");
  }
  return sToTrim;
}

function replaceAll(find, replace, string) {
  if (find == replace) return string;
  while (true) {
	  var oldString = string;
	  string = string.replace(find, replace);
	  if (string == oldString) return string;
  }
}

	
function removeAbsoluteLinks(html) {
  var absPath = document.location.protocol + '//' + document.location.host+document.location.pathname;
  if (absPath.match(/\/([^\/]*)\/(forward|index)\.php$/)) {
    var absPath2 = document.location.protocol + '//' + document.location.host+":"+document.location.port+document.location.pathname;
    var currentProject = RegExp.$1;
    var paths = new Array(absPath, absPath2);
    for (var i = 0; i < paths.length; i++) {
      paths[i] = paths[i].replace(/\/(forward|index)\.php$/, '/');
      html = replaceAll(paths[i]+"index.php", "index.php", html);
      html = replaceAll(paths[i]+"data/", "data/", html);
      html = replaceAll(paths[i]+"templates/", "templates/", html);
      html = replaceAll(ctsWebsite+"/../"+ctsWebsite, ctsWebsite, html);
      html = replaceAll(paths[i], "../"+currentProject+"/", html);
    }
  }
  return html;
}

function selectPopupRow(tr){
  tr.style.backgroundColor = 'rgb(252, 238, 196)'; 
  tr.children[0].style.filter = '';
  tr.children[0].style.paddingTop = '0px';
  tr.children[0].style.paddingBottom = '0px';
  tr.children[0].style.borderWidth = '1px 0px';
  tr.children[0].style.borderTopColor = 'rgb(4,2,132)';
  tr.children[0].style.borderBottomColor = 'rgb(4,2,132)';
  tr.children[1].style.borderTopColor = 'rgb(4,2,132)';
  tr.children[1].style.borderBottomColor = 'rgb(4,2,132)';
  tr.children[2].style.borderTopColor = 'rgb(4,2,132)';
  tr.children[2].style.borderBottomColor = 'rgb(4,2,132)';
}

function deselectPopupRow(tr){
  tr.style.backgroundColor = 'rgb(244,246,244)'; 
  tr.children[0].style.filter = "progid:DXImageTransform.Microsoft.Gradient(GradientType=1, StartColorStr='#E4EEFC', EndColorStr='#84AEE4')";
  tr.children[0].style.paddingTop = '1px';
  tr.children[0].style.paddingBottom = '1px';
  tr.children[0].style.borderWidth = '0px 0px';
  tr.children[1].style.borderTopColor = 'rgb(244,246,244)';
  tr.children[1].style.borderBottomColor = 'rgb(244,246,244)';
  tr.children[2].style.borderTopColor = 'rgb(244,246,244)';
  tr.children[2].style.borderBottomColor = 'rgb(244,246,244)';
}

function getHelperIFrame(name) {
  if (!csHelperIFrames[name]) {
    var iframe = document.createElement("iframe");
    iframe.style.cssText = 'visibility:hidden;width:1px;height:1px;position:absolute';
    // iframe.src = "../admin/blank.htm";
    document.body.appendChild(iframe);
    csHelperIFrames[name] = iframe;
  }
  return csHelperIFrames[name];
}

function showPopup(src, evt) {
  if (popupLoader == null) {
    popupLoader = document.createElement("iframe");
    popupLoader.style.display = "none";
    document.body.appendChild(popupLoader);
    registerEvent(popupLoader, "load", popupLoaded);
  }
  popupIsLoading = true;
  popupLoader.event = evt ? evt : window.event;
  popupLoader.src = src;
  return false;
}

function popupLoaded() {
  if(popupIsLoading) displayPopup(popupLoader, popupLoader.event);
}

function displayPopup(content, event, width, cssText) {
  if (isFirefox) {
    var x = event.pageX;
    var y = event.pageY;
  } else {
    if (!event) event = window.event;
    var x = event.screenX;
    var y = event.screenY;
  }
  if (!width) width = 200;
  if (!cssText) cssText = "margin:0px;padding:0px;border:0px; font-family:Tahoma; font-size:8pt;background-color:rgb(252,250,244);";
  if (!popup) preparePopupWindow();
  if (isFirefox) {
    if (content.contentDocument) content = content.contentDocument.body.innerHTML;
    var body = popup.firstChild.contentDocument.body;
    popup.style.width = width;
  } else {
    if (content.contentWindow) content = content.contentWindow.document.body.innerHTML;
    var body = popup.document.body;
  }
  body.onContextMenu = 'return false;'
  body.innerHTML = content;
  body.style.cssText = cssText;
  body.style.overflow="hidden";
  var height = calculateHeight(body, width);
  popup.show(x, y, width, height);
}

function preparePopupWindow (){
  if (isFirefox) {
    popup = document.createElement("div");
    popup.style.cssText="position:absolute;display:none;border:0px;margin:0px;padding:0px;z-index:9999999999999";

    popup.hide = function() {popup.style.display = "none";}
    popup.show = function(left, top, width, height) {
      popup.style.width = width;
      popup.style.height = height;
      popup.style.left = Math.max(0, Math.min(left,window.innerWidth-width + window.scrollX));
      popup.style.top = Math.max(0, Math.min(top,window.innerHeight-height + window.scrollY));
      popup.style.display = "block";
      popup.firstChild.contentWindow.focus();
    }
    var iframe = document.createElement("iframe");
    iframe.style.cssText = "border:0px;margin:0px;padding:0px;width:100%;height:100%;overflow:hidden";
    popup.appendChild(iframe);
    document.body.appendChild(popup);
    iframe.contentDocument.close();
    iframe.contentDocument.open();
    iframe.contentDocument.write("<html><head><style>body {border: 0px;margin: 0px;padding: 0px;overflow:hidden}</style></head><body></body></html>");
    iframe.contentDocument.close();
    popup.firstChild.contentWindow.onblur = popup.hide;
  } else {
    popup = window.createPopup();
  }
  return popup;
}

function getOffset(component, parentOffsets) {
  if (!parentOffsets) parentOffsets = {'x':0, 'y':0};
  if (!component) return parentOffsets;
  if (component.style && component.style.left) {
     parentOffsets['x'] += parseUnit(component.style.left, "px", "px");
  } else if (component.offsetLeft) {
     parentOffsets['x'] += component.offsetLeft;
  }
  if (component.style && component.style.top) {
     parentOffsets['y'] += parseUnit(component.style.top, "px", "px");
  } else if (component.offsetTop) {
    parentOffsets['y'] += component.offsetTop;
  }
  if (!component.offsetLeft && !component.offsetTop) {
    // bugfix because IE doesn't calculate offset correct, if a div is directly added to a table
    if (!isFirefox && component.parentNode && component.parentNode.tagName && component.parentNode.tagName.toLowerCase() == "td") {
      var table = component.parentNode;
      while (table && table.tagName && table.tagName.toLowerCase() != "table") table = table.parentNode;
      if (table && table.parentNode) {
        parentOffsets['x'] += 2 + table.parentNode.clientLeft;
        parentOffsets['y'] += 2 + table.parentNode.clientTop;
      }
    }
  }
  return getOffset(component.offsetParent, parentOffsets);
}

function calculateHeight(component, width) {
  var srcText = component.innerHTML.substr((component.innerHTML.search("windowheight") + 14));
  var height = parseInt(srcText.substr(0, srcText.search(/\"/)));
  if (!height) {
    var heightCalculater = document.createElement("span");
    heightCalculater.style.width = width;
    heightCalculater.innerHTML = "<span>"+outerHTML(component)+"</span><div>&nbsp;</div>";
    heightCalculater.style.zIndex = 9999999;
    heightCalculater.style.position = "absolute";
    heightCalculater.style.visibility = "hidden";
    document.body.appendChild(heightCalculater);
    height = heightCalculater.lastChild.offsetTop - heightCalculater.firstChild.offsetTop;
    document.body.removeChild(heightCalculater);
  }
  height += isFirefox ? POPUP_HEIGHT_ADD_FF : POPUP_HEIGHT_ADD_IE;
  return height;
}


// doesn't work
function getDimension(component, addX, addY) {
  if (!addX) addX = 0;
  if (!addY) addY = 0;
  addX += component.offsetLeft;
  addY += component.offsetTop;
  var dimension = {'x': addX + 0,
                   'y': addY + 0};
  if (component.childNodes) {
    for (var i = 0; i < component.childNodes.length; i++) {
      var newDimension = getDimension(component.childNodes[i], addX, addY);
      if (newDimension['x'] > dimension['x']) dimension['x'] = newDimension['x'];
      if (newDimension['y'] > dimension['y']) dimension['y'] = newDimension['y'];
    }
  }
  return dimension;
}

function getNodeWidth(node, useOffset) {
  if (!node) return 0;
  if (node.style && parseFloat(node.style.width) > 0 && (""+node.style.width).indexOf("%") == -1) {
    if (useOffset && node.style.overflow && node.style.overflow.toLowerCase() != "hidden" && node.tagName.toLowerCase() != "img" && parseUnit(node.style.width, "px", "px") < node.offsetWidth) {
      return node.offsetWidth;
    } else {
      return parseUnit(node.style.width, "px", "px");
    }
  }
  if (useOffset && node.offsetWidth > 0) return node.offsetWidth;
  return getNodeWidth(node.parentNode);
}

function getNodeHeight(node, useOffset) {
  if (!node) return 0;
  if (node.style && parseFloat(node.style.height) > 0 && (""+node.style.height).indexOf("%") == -1) {
    if (useOffset && node.style.overflow && node.style.overflow.toLowerCase() != "hidden" && node.tagName.toLowerCase() != "img" && parseUnit(node.style.height, "px", "px") < node.offsetHeight) {
      return node.offsetHeight;
    } else {
      return parseUnit(node.style.height, "px", "px");
    }
  }
  if (useOffset && node.offsetHeight > 0) return node.offsetHeight;
  return getNodeHeight(node.parentNode);
}

function parseUnit(unit, dstUnit, defaultUnit) {
  var DPI = 96;
  unit = ""+unit
  var number = parseFloat(unit.replace(/[,]/g,"."));
  if (isNaN(number)) return 0;
  var srcUnit = unit.substr((""+number).length).toLowerCase();
  switch (srcUnit) {
    case 'mm': var mm = number; break;
    case 'cm': var mm = number * 10; break;
    case 'pt': var mm = number * 0.351; break;
    case 'in': var mm = number * 25.4; break;
    case 'px': var mm = number * 25.4 / DPI; break;
    default:
      if (defaultUnit) {
        return parseUnit(number+defaultUnit, dstUnit);
      } else {
        alert("srcUnit "+srcUnit +" is not definied in function changeUnit"); return number;
      }
  }
  switch (dstUnit.toLowerCase()) {
    case 'mm': return (mm);
    case 'cm': return (mm / 10); break;
    case 'pt': return  (mm / 0.351); break;
    case 'in': return (mm / 25.4); break;
    case 'px': return (mm / 25.4 * DPI); break;
    default: alert("dstUnit "+dstUnit +" is not definied in function changeUnit"); return number;
  }
}

function round(number, digits) {
  if (!digits) digits = 0;
  if (digits == 0) return Math.round(number);
  var multiply = Math.pow(10, digits);
  var rounded = Math.round(number * multiply);
  var roundString = "" + rounded;
  while (roundString.length <= digits) roundString = "0"+roundString;
  roundString = roundString.substring(0, roundString.length - digits) +"."+ roundString.substring(roundString.length - digits);
  return roundString;
}

function getCPositionX(width){
  if(isFirefox){
    var posX  = window.screenX + (window.outerWidth - width) / 2; 
  }else{
    var posX = (screen.width- width) / 2;
  }
  return posX;
}

function getCPositionY(Height){
  if(isFirefox){
    var posY  = window.screenY + (window.outerHeight - Height) / 2; 
  }else{
    var posY = (screen.height - Height) / 2;
  }
  return posY;
}

/** returns a Array with the name of the element as first element and the path as second */
function getDOMPath(element, displayElementNames) {
  if (!element) return "";
  if (element.scopeName == "cs") {
    var nodeName = "cs:"+element.nodeName;
  } else {
    var nodeName = element.nodeName.toLowerCase();
  } 
  var title = nodeName + (displayElementNames && element.name ? "["+element.name+"]" : "");
  var component = element.parentNode;
  var subTitle = "";
  while(component != null && (component.nodeName.toLowerCase() != "form" || component.name != "sissi2") && component.nodeName.toLowerCase() != "body" && component.nodeName.toLowerCase() != "pageset"&& component.getAttribute) {
    var nodeName = null;
    if (!component.getAttribute("hide_at_parsing")  && !component.getAttribute("remove_at_parsing")) {
      if (component.scopeName == "cs") {
        nodeName = "cs:"+component.nodeName;
      } else {
        nodeName = component.nodeName.toLowerCase();
      } 
      if (nodeName != null) {
        if (displayElementNames && component.name) nodeName += "["+component.name+"]";
        subTitle = nodeName + "/ " + subTitle;
      }
    }
    component = component.parentNode;
  }
  return new Array(title, subTitle);
}

function registerJavascriptErrorHandler() {
  window.onerror = fnHandleJavascriptErrors;
}

function fnHandleJavascriptErrors(errorMessage, url, line){
  ALL_JAVASCRIPT_ERRORS[ALL_JAVASCRIPT_ERRORS.length] = url + " (" +line+") " + errorMessage  +"\n";
  return true;
}

function createErrorMessage(err, addToMessage) {
  if (addToMessage) err.message = addToMessage + " - " + err.message;
  ALL_JAVASCRIPT_ERRORS[ALL_JAVASCRIPT_ERRORS.length] = (err.number & 0xffff) +" : "+ err.message;
}
