// numeric format constants *****************************************
var USDECIMAL =     ".";
var GERMANDECIMAL = ",";
var DECIMAL =       USDECIMAL;
var INTEGER =       "";

// operator constants ***********************************************
var GT = ">";
var GTE = ">=";
var LT = "<";
var LTE = "<=";
var EQUAL = "==";
var BETWEEN = "[]";

var ERR_ERROR   = 0;
var ERR_NOERROR = 1;

// alpha check ******************************************************
var ALPHANUMERIC    = /^[0-9a-zA-Z???????]*$/;
var ALPHA           = /^[a-zA-Z???????]*$/;

/**
* checks for correct email address
**/
function isValidEMail(email){
  var emailExpression = /^[A-Za-z0-9.!#$%&*+-\/=?^_{|}~]{2,}@[A-Za-z0-9.!#$%&*+-\/=?^_{|}~]{3,}\.[a-zA-Z]{2,3}$/;
  return emailExpression.test(email);
}

/**
 * checks time string for matching the pattern.
 * CAUTION : for now only four simple patterns are supported
 *	 	"HH:mm:ss" (i.e. time can be "20:34:59")
 *	 	"HH:mm" (i.e. time can be "20:34")
 *  	"hh:mm:ss aa" ("08:34:59 PM")
 *  	"hh:mm aa" ("08:34 PM")
 * wer Zeit und Lust hat mehr patterns zu implementieren : bitte schoen ! :-)
 */
function isValidTime(time, pattern)
{
  if (time == "")
	return true;

  var regex;
  if(pattern == "hh:mm aa")
  {
      regex = /^((([0]?[1-9]|1[0-2]):([0-5][0-9])) [AaPp][Mm])$/;
  }
  else if(pattern == "hh:mm:ss aa")
  {
      regex = /^((([0]?[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9])) [AaPp][Mm])$/;
  }
  else if(pattern == "HH:mm")
  {
      regex = /^((0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9]))$/;
  }
  else if(pattern == "HH:mm:ss")
  {
      regex = /^((0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]))$/;
  }
  else
  {
      return false;
  }
  
  return regex.test(time);
}



function isValidDate(objValue, format, op, date2, date3){
  var inDate = objValue;
  if ((inDate == "")||(inDate==null)||(typeof(inDate) == "undefined")){
    var d = new Date();
	d.setTime(0);
	return d;
  }
  if (inDate.indexOf('>') == 0 || inDate.indexOf('<') == 0)
	inDate = inDate.substring(1,inDate.length);
  return _checkDate(inDate,format, op, date2, date3);
}

function isNumber(objValue){
  // VK 25.03.2004
  //return checkNumeric(objValue, ",") || checkNumeric(objValue, ".");
  return checkNumeric(objValue, ",.") || checkNumeric(objValue, ".,");
}

function isInteger(value){
    var x = ""+parseInt(value);
    return (value == x);
}

function isAlpha(str){
    return ALPHA.test(str);
}

function isAlphaNumeric(str){
    return ALPHANUMERIC.test(str);
}

function checkNumeric(objValue, format, op, value2, value3){
   return _checkNumeric(objValue, format, op, value2, value3)?1:0;
}

function checkDate(objValue, format, op, date2, date3){
	return _checkDate(objValue, format, op, date2, date3)?1:0;
}


function getArgLength(args){
	var nArgCount = 0;
	for(var i=0;i<args.length;i++){
		if(typeof(args[i]) != "undefined"){
			nArgCount++;
		}
	}
	return nArgCount;
}

//start private methods


// era change
var _change = 30;

function _checkNumeric(objValue, format, op, value2, value3)
{
    var parameters = getArgLength(_checkNumeric.arguments);
    var obj1;

    if (parameters == 2)
    {
        obj1 = new NumericObject(objValue, format);
        return obj1 && obj1.isValidNumber;
    }
    else if (parameters == 4)
    {
        obj1 = new NumericObject(objValue, format);
        if (!obj1 || !obj1.isValidNumber)
             return false;
        return operat(op, obj1.value, parseFloat(value2));
    }
    else if (parameters == 5)
    {
        obj1 = new NumericObject(objValue, format);
        if (!obj1 || !obj1.isValidNumber)
             return false;
        return operat(op, obj1.value, parseFloat(value2), parseFloat(value3));
    }
    return false;
}


function _checkDate(objValue, format, op, date2, date3)
{
    var parameters = getArgLength(_checkDate.arguments);
    var obj1, obj2, obj3;

    if (parameters == 2)
    {
        obj1 = new DateObject(objValue, format);
        if(obj1 && obj1.isValidDate){
        	var d = new Date();
        	d.setTime(obj1.value);
        	return d;
        }
        return false;
    }
    else if (parameters == 4)
    {
        obj1 = new DateObject(objValue, format);
        obj2 = new DateObject(date2, format);

        if (!obj1 || !obj1.isValidDate
	 || !obj2 || !obj2.isValidDate)
           return false;
        return operat(op, obj1.value, obj2.value);
    }
    else if (parameters == 5)
    {
        obj1 = new DateObject(objValue, format);
        obj2 = new DateObject(date2, format);
        obj3 = new DateObject(date3, format);

        if (!obj1 || !obj1.isValidDate
	 || !obj2 || !obj2.isValidDate
	 || !obj3 || !obj3.isValidDate)
                return false;
        return operat(op, obj1.value, obj2.value, obj3.value);
    }
    return false;
}

/**
 * FormatPattern object is used for representation of format patterns,
 * that must be formed in compliance with following schema :
 * [<grouping_separator>][<decimal_separator>][<decimal_digits>]
 *
 * where :
 * grouping_separator := .|,|_
 * decimal_separator := .|,|_
 * decimal_digit := 9*
 *
 * The parameter <code>paramFormat</code> will be parsed and we have
 * as result a FormatPattern object with following fields :
 *  - groupingSeparator  - grouping separator (character)
 *  - decimalSeparator - decimal separator (character)
 *	- decimalPlaces - number of REQUIRED decimal places (if none specified - any number of decimal places allowed)
 *  - value - string representation of format pattern
 *
 * If one (or both) separator are missing it will be replaced by '_' (underscore)
 * Underscore means: for grouping separator - no grouping separators allowed;
 * for decimal separator - no decimal digits allowed.
 *
 * Caution! Patterns "._99", ",_99" etc. are contradictory, that is
 * they are not allowed.
 *
 * Examples of valid patterns :
 *
 * parameter value = ".,"
 *
 *		grouping separator =.
 *		decimal separator =,
 *		decimal places = 0
 *		value = ".,"
 *
 * parameter value = "_,99"
 *
 *		grouping separator =_
 *		decimal separator =,
 *		decimal places = 2
 *		value = "_,"
 *
 * parameter value = "._"
 *
 *		grouping separator =.
 *		decimal separator =_
 *		decimal places = 0
 *		value = ".,"
 *
 * parameter value = ","
 *
 *		grouping separator =_
 *		decimal separator =,
 *		decimal places = 0
 *		value = ".,"
 *
 * parameter value = "."
 *
 *		grouping separator =_
 *		decimal separator =.
 *		decimal places = 0
 *		value = ".,"
 *
 */
function FormatPattern(paramFormat)
{
	var sPattern = paramFormat;

  if((sPattern == null)||(sPattern == "")||(typeof(sPattern)=="undefined"))
  {
    sPattern = "_" + "_";
  }

  while(sPattern.length < 2 || sPattern.charAt(0) == '9' || sPattern.charAt(1) == '9')
  {
  	sPattern = "_" + sPattern;
  }

  this.groupingSeparator = sPattern.charAt(0);
  this.decimalSeparator  = sPattern.charAt(1);
  this.decimalPlaces 	 = sPattern.length - 2;

  if((this.decimalPlaces==0)&&(this.decimalSeparator!='_'))
  {
		this.decimalPlaces=-1; //compliance with java version
  }

  this.value = sPattern;
  this.toString = function(){return this.value};

}

function NumericObject(strVal, format)
{
	this.value = "";
	var strValue = ""+strVal;
	var pattern = new FormatPattern(format);

	this.isValidNumber = false;

	var decimalSeparatorIndex = strValue.lastIndexOf(pattern.decimalSeparator);
	this.leftSide = strValue.substring(0, decimalSeparatorIndex==-1?strValue.length:decimalSeparatorIndex);
	this.rightSide = "";
	if(pattern.decimalSeparator != '_')
	{
		this.rightSide = strValue.substring(decimalSeparatorIndex==-1?strValue.length:(decimalSeparatorIndex+1), strValue.length);
	}
	else // decimal separator is undescore, that is no decimal places alowed
	{
		if(decimalSeparatorIndex!=-1)
		{
			return;
		}
	}
	if(pattern.groupingSeparator=='.')
	{
		this.leftSide = this.leftSide.replace(/\./g, "" );
	}
	else if(pattern.groupingSeparator==',')
	{
		this.leftSide = this.leftSide.replace(/,/g, "" );
	}
	else if(pattern.groupingSeparator=='_')
	{
		;// replace nothing
	}

	if(/^[+-]?[0-9]+$/.test(this.leftSide)&&(this.rightSide==""?true:/^[0-9]+$/.test(this.rightSide))&&(pattern.decimalPlaces < 0 || this.rightSide.length<=pattern.decimalPlaces))
	{
		this.isValidNumber = true;
		this.value = parseFloat(this.leftSide + "." + this.rightSide);
	}
}

function DateObject(objValue, formatString)
{
    var format = formatString;
    var strValue = objValue;

    this.isValidDate = false;

    //construct regular expression from input format
    var dateCheck = format;
    dateCheck = dateCheck.replace("dd", "([012][1-9]|[123][01])");
    dateCheck = dateCheck.replace("MM", "(0[1-9]|1[012])");
    if(dateCheck.indexOf("yyyy") > -1) {
	dateCheck = dateCheck.replace("yyyy", "([0-9]{4})");
    }else{
	dateCheck = dateCheck.replace("yy", "([0-9]{2})");
    }
    dateCheck = dateCheck.replace(/\./g, "\\.");
    dateCheck = dateCheck.replace(/\//g, "\\/");
    dateCheck = "/^" + dateCheck + "$/";
    dateCheck = eval(dateCheck);

    var ind = _getIndexArray(format);
    var erg;

    if (dateCheck && ind)
    {
        erg = dateCheck.exec(objValue);
        if (erg)
        {
			var year = "";
			var month = "";
			var day = "";
			for(var i=0;i<3;i++){
				var nType = parseInt(ind[i], 10);
				if(nType == 1)
					year = erg[i+1];
				else if(nType == 2)
					month = erg[i+1];
				else if(nType == 3)
					day = erg[i+1];
			}
			year = year*1;
	        if (year >= 0 && year < _change)
	            year += 2000;
	        else if (year >= _change && year <= 99)
	            year += 1900;
	        this.dateValue = new Date(year, month - 1, day);
	        this.value = this.dateValue.getTime();
	        this.isValidDate = ((this.dateValue.getMonth()+1) == month);
        }
        else
            this.isValidDate = false;
    }else{
        this.isValidDate = false;
    }
}


function _getIndexArray(str)
{
    var dayind = str.indexOf("dd");
    var monind = str.indexOf("MM");
    var yearind = str.indexOf("yy");
    var n1 = 0;
    var n2 = 0;
    var n3 = 0;
    if(yearind < monind && yearind < dayind){
	n1 = 1;
	if(monind < dayind){
		n2 = 2;
		n3 = 3;
	}else{
		n2 = 3;
		n3 = 2;
	}
    }
    if(dayind < monind && dayind < yearind){
	n1 = 3;
	if(monind < yearind){
		n2 = 2;
		n3 = 1;
	}else{
		n2 = 1;
		n3 = 2;
	}
    }
    if(monind < yearind && monind < dayind){
	n1 = 2;
	if(dayind < yearind){
		n2 = 3;
		n3 = 1;
	}else{
		n2 = 1;
		n3 = 3;
	}
    }
    return new Array(n1,n2,n3);
}



function operat(op, val1, val2, val3)
{
    var params = operat.arguments.length;
    if (params == 3){
        switch (op)
        {
            case ">":
                return val1 > val2;
            case ">=":
                return val1 >= val2;
            case "<":
                return val1 < val2;
            case "<=":
                return val1 <= val2;
            case "<>":
                return val1 != val2;
            case "!=":
                return val1 != val2;
            case "==":
                return val1 == val2;
        }
    }else if (params == 4){
        if (val2 > val3)
        {
            var tmp = val3;
            val3 = val2;
            val2 = tmp;
        }
        switch (op)
        {
            case "[]":
                return (val1 >= val2) && (val1 <= val3);
            case "][":
                return (val1 < val2) || (val1 > val3);
            case "()":
                return (val1 > val2) && (val1 < val3);
            case ")(":
                return (val1 <= val2) || (val1 >= val3);
        }
    }
    return false;
}

function smarti_print(printurl, reload, url){
	var myurl = url + "?printurl=" + _escape(printurl) + (reload?"&reloadopener=true":"");
	var win = window.open(myurl,"PrintOrders","scrollbars=no,resizable=yes,width=700,height=400,left=50,top=100");
	win.focus();
	return win;
}

function _escape(str){
	var ret = "";
	for(var i=0;i<str.length;i++){
		var n = str.charCodeAt(i);
		if( (n >= 48 && n <= 57) || (n >= 65 && n <= 90) || (n >= 97 && n <= 122))
			ret += str.charAt(i);
		else
			ret += "%"+dx(n);
	}
	return ret;
}

function dx(d){
 var z = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
 var x = "";
 var i = 1, v = d;
 while(v > 15)
 		v = Math.floor(v / 16); i++;
 v = d;
 for(j=i;j>=1;j--){
	 x = x + z[Math.floor(v / Math.pow(16,j-1))];
	 v = v - (Math.floor(v / Math.pow(16,j-1)) * Math.pow(16,j-1));
 }
 return x;
}

function convertNls(s){
 var r=/&#(\d{1,5});/;
 while(s.search( r )!=-1) s=s.replace(r,String.fromCharCode(RegExp.$1));
 return s;
}

function ufirm(s){
 return(confirm(convertNls(s)));
}

function ulert(s){
 alert(convertNls(s));
}

function uprompt(s, value){
 return(prompt(convertNls(s), value));
}

function needToHide(objid,evt){
	  if(!evt)
	   evt = window.event; //IE
	  var obj = document.getElementById(objid);
	  var src  = typeof(evt.fromElement) != "undefined" ? evt.fromElement : evt.target;
	  var dest = typeof(evt.toElement) != "undefined" ? evt.toElement : evt.relatedTarget;

	  if((src!=null)&&(dest!=null)&&(src == obj || isChildOf(src,obj)) && dest != obj && !isChildOf(dest, obj)){
		return true;
	  }
	  return false;
}

function isChildOf(o1,o2){
	  if(typeof(o1) == "undefined" || typeof(o2) == "undefined")
	    return false;

      try
      {
	    while(o1.parentNode)
	    {
  	      if(o1.parentNode == o2)
	        return true;
	      o1 = o1.parentNode;
	    }
      }
      catch(e)
      {
        // Access denied exception in mozilla-based browsers
      }

      return false;
}


function getStyleValue(obj, property) {
  var value;
  if(document.defaultView) {  /* works for all except IE */
    value = document.defaultView.getComputedStyle(obj, null).getPropertyValue(property);
  }
  else if(obj.currentStyle) {   /* IE */
    value = obj.currentStyle[property];
  }
  return value;
}

function findPosX(obj){
  var curleft = 0;
  if (obj.offsetParent)
  {
	while (obj.offsetParent)
	{
	  curleft += obj.offsetLeft
	  obj = obj.offsetParent;
	}
  }
  else if (obj.x)
  {
    curleft += obj.x;
  }
  return curleft;
}


function findPosXInContainer(obj){
  var curleft = 0;
  while (obj.offsetParent) {
      curleft += obj.offsetLeft;
	  obj = obj.offsetParent;
      if (getStyleValue(obj, "position") != "static") {
          break;
      }
  }
  return curleft;
}

function findPosY(obj){
  var curtop = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curtop += obj.offsetTop
      curtop -= obj.scrollTop
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
  {
    curtop += obj.y;
  }
  return curtop;
}


function findPosYInContainer(obj){
  var curtop = 0;
  while (obj.offsetParent) {
      curtop += obj.offsetTop;
      curtop -= obj.scrollTop;
      obj = obj.offsetParent;
      if (getStyleValue(obj, "position") != "static") {
          break;
      }
  }
  return curtop;
}


// Adds an additional Parameter to an url
//------------------------------------------------------------------
function addParameter(url,parameter) {
  return url+((url.indexOf('?')!=-1)?'&':'?')+parameter;
}

function addOrReplaceParameter(url,parameter) {
    if(url.indexOf('?') == -1) {
        return addParameter(url,parameter);
    }
    var parKey = parameter.replace(/=.*/,'');
    var urlParams = url.replace(/.*\?/,'');
    var strBegin = urlParams.indexOf(parKey);
    if(strBegin == -1){
        return addParameter(url,parameter);
    } else {
        var reg = new RegExp("(.*\?.*)"+parKey+"=[^&]*(.*)");
        reg.exec(url);
        return RegExp.$1+parameter+RegExp.$2;
    }
}

function getUrlParameter(paramName) {
	var currentUrl = window.location.search;
	var strBegin = currentUrl.indexOf(paramName);;
	if(strBegin == -1){
	  return "";
	}else{
	  strBegin += paramName.length + 1;
	}
	var strEnd = currentUrl.indexOf("&",strBegin);
	if (strEnd==-1)
		strEnd = currentUrl.length;
	return currentUrl.substring(strBegin,strEnd);
}


// new version:
function getWindowHeight()
{
    var netscape =(window.innerHeight) ? 1:0;// Netscape Navigator
    var IE = (document.all) ? 1:0;// or Internet Explorer

    var WindowHeight=600;
    if(IE) {
        WindowHeight = parent.document.body.clientHeight;
    }
    if(netscape) {
        WindowHeight = parent.window.innerHeight;
    }

    return WindowHeight;
}

function getWindowWidth()
{
    var WindowWidth = 1024;

    if (window.innerWidth)
        WindowWidth = window.innerWidth;
    else if (document.documentElement &&
        document.documentElement.clientWidth &&
        document.documentElement.clientWidth > 0)
        WindowWidth = document.documentElement.clientWidth;
    else if (document && document.body && document.body.clientHeight)
        WindowWidth = document.body.clientWidth;

    return WindowWidth;
}

var setpointer_objs = [];
var setpointer_colors = [];
setpointer_colors[0] =  '#FFE5E5';
setpointer_colors[1] =  '#F0D8DC';

function setColor(color1, color2) {
 if(typeof color2=='undefined')
   color2=color1;
 setpointer_colors[0] = color1;
 setpointer_colors[1] = color2;
}

function setPointer(obj, type, nRow){
	if(type == 'over'){
		for(var i=0;i<obj.parentNode.childNodes.length;i++){
			var obj = obj.parentNode.childNodes[i];
			if(obj.nodeName != "TD")
				continue;
			setpointer_objs[obj]	= obj.style.backgroundColor;
			obj.style.backgroundColor = setpointer_colors[nRow%2];
		}
	}
	if(type == 'out'){
		for(var i=0;i<obj.parentNode.childNodes.length;i++){
			var obj = obj.parentNode.childNodes[i];
			if(obj.nodeName != "TD")
				continue;
			obj.style.backgroundColor = setpointer_objs[obj];
		}
	}
	if(type == 'click'){
		click(nRow);
	}
}

function scrollableTable(tableHeight, headlineRows, tableId) {
  var scrollbarOffset = 17;

  // Checks for parameters
  if (typeof(tableId) == 'undefined') {
    tableId = 'scrollabletable';
  }
  
  contentTable = document.getElementById(tableId);
  if (contentTable == null) {
    return;
  }

  if (typeof(tableHeight) == 'undefined') {
    tableHeight = 300;
  }

  if (contentTable.offsetHeight < tableHeight) {
    return;
  }

  if (typeof(headlineRows) == 'undefined') {
    headlineRows = 1;
  }

  // Add div to wrap head and body
  var mainDiv = document.createElement("div");
  mainDiv.style.textAlign = 'left';
  mainDiv.style.height = tableHeight;
  contentTable.parentNode.insertBefore(mainDiv, contentTable);

  // Remove table div, which will be added as child of mainDiv
  mainDiv.parentNode.removeChild(contentTable);

  // Add div for head
  var divHead = document.createElement("div");
  mainDiv.appendChild(divHead);

  // Add table to head
  divHead.appendChild(contentTable);

  // clone div and append to main div for body
  divBody = divHead.cloneNode(true);
  mainDiv.appendChild(divBody);

  tabHead = divHead.getElementsByTagName('table')[0];
  tabBody = divBody.getElementsByTagName('table')[0];

  // Set width of tables to width of table minus offset for the scollbar (because of possible 100% width)
  tableWidth = Math.ceil((tabBody.offsetWidth - scrollbarOffset) / 2) * 2;
  tabHead.style.width = tableWidth;
  tabBody.style.width = tableWidth;

  // Set width of divs to width of table and add offset for the scollbar in body
  tableWidth = Math.ceil(tabBody.offsetWidth / 2) * 2;
  divHead.style.width = tableWidth;
  divBody.style.width = Math.ceil((tabBody.offsetWidth + scrollbarOffset) / 2) * 2;

  // Get height of headlines (table will not be visible)
  tabForHeadHeight = tabHead.cloneNode(true);
  tabForHeadHeight.style.height = 0;
  divHead.appendChild(tabForHeadHeight);
  // Remove all rows not part of the head
  while (tabForHeadHeight.rows.length > headlineRows) {
    tabForHeadHeight.deleteRow(tabForHeadHeight.rows.length - 1);
  }
  headlineHeight = tabForHeadHeight.offsetHeight;

  // For IE: select fields in body table must be invisible, 
  // because they will show up otherwise in front of headline.
  // Also rename all fields, which are only to keep size of columns
  selectElements = tabBody.getElementsByTagName('select');
  for (i = 0; i < tabForHeadHeight.getElementsByTagName('select').length; i++) {
    selectElements[i].style.visibility = 'hidden';
    selectElements[i].name = selectElements[i].name + 'ForScrolling';
  }
  selectElements = tabHead.getElementsByTagName('select');
  for (i = tabForHeadHeight.getElementsByTagName('select').length; i < selectElements.length; i++) {
    selectElements[i].name = selectElements[i].name + 'ForScrolling';
  }
  selectElements = tabForHeadHeight.getElementsByTagName('select');
  for (i = 0; i < selectElements.length; i++) {
    selectElements[i].name = selectElements[i].name + 'ForScrolling';
  }

  // Rename input fields to solve problems in servlet
  inputElements = tabBody.getElementsByTagName('input');
  for (i = 0; i < tabForHeadHeight.getElementsByTagName('input').length; i++) {
    inputElements[i].name = inputElements[i].name + 'ForScrolling';
  }
  inputElements = tabHead.getElementsByTagName('input');
  for (i = tabForHeadHeight.getElementsByTagName('input').length; i < inputElements.length; i++) {
    inputElements[i].name = inputElements[i].name + 'ForScrolling';
  }
  inputElements = tabForHeadHeight.getElementsByTagName('input');
  for (i = 0; i < inputElements.length; i++) {
    inputElements[i].name = inputElements[i].name + 'ForScrolling';
  }

  // Set style values for elements
  divHead.style.className = tabHead.style.className + '_scrollhead';
  divHead.style.position = 'relative';
  divHead.style.zIndex = 200;
  divHead.style.height = headlineHeight;
  divHead.style.overflow = 'hidden';
  divBody.style.className = tabHead.style.className + '_scrollbody';
  divBody.style.overflowX = 'hidden';
  divBody.style.overflowY = 'auto';
  divBody.style.position = 'relative';
  divBody.style.zIndex = 100;
  divBody.style.height = tableHeight;

  // The body div must be moved upwards by the height of the headline rows
  divBody.style.top = -headlineHeight;
}
