/**
 * Holds some variables to check which browser is used.
 * Note: a browser independent webapp doesn't need these checks!
 */
var Browser = {
	IE: !!(window.attachEvent && !window.opera),
	Opera: !!window.opera,
	WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
	Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
};

/**
 * Cuts all leading white-spaces of a <code>String</code>.
 */
String.prototype.ltrim = function () {
  return this.replace(/^\s+/,"");
};

/**
 * Cuts all trailing white-spaces of a <code>String</code>.
 */
String.prototype.rtrim = function () {
  return this.replace(/\s+$/,"");
};

/**
 * Cuts all leading and trailing white-spaces of a <code>String</code>.
 */
String.prototype.trim = function () {
  return this.replace(/^\s+/,"").replace(/\s+$/,"");
};

/**
 * Removes all withespaces.
 */
String.prototype.removeWhiteSpaces = function () {
  return(this.replace(/\s+/g,""));
};

/**
 * Checks whether the <code>String</code> represents a signed <code>int</code>
 * or not.
 */
String.prototype.isSignedInt = function () {
  return this.search(/^((\+|\-){1}\d+)?$/) != -1;
};

/**
 * Checks whether the <code>String</code> represents an unsigned <code>int</code>
 * or not.
 */
String.prototype.isUnsignedInt = function () {
  return this.search(/^\d*$/) != -1;
};

/**
 * Checks whether the <code>String</code> represents an <code>int</code> or not.
 */
String.prototype.isInt = function () {
  return this.search(/^((\+|\-)?\d+)?$/) != -1;
};

/**
 * Checks whether the <code>String</code> represents a <code>float</code> or not.
 */
String.prototype.isFloat = function () {
  return this.search(/^(((\+|\-)?\d+){1}(\.\d+)?)?$/) != -1;
};

/**
 * Checks whether the <code>String</code> represents a strict <code>float</code>
 * or not.
 */
String.prototype.isStrictFloat = function () {
  return this.search(/^(((\+|\-)?\d+){1}(\.\d+){1})?$/) != -1;
};

/**
 * Checks whether the <code>String</code> ends with zeros and removes them if so.
 */
String.prototype.cleanFloat = function () {
  return this.replace(/(\.{1}0+)|0+$/,"");
};

/**
 * Checks whether the <code>String</code> represents a year or not.
 */
String.prototype.isYear = function () {
  return this.search(/^\d{4}$/) != -1;
};

/**
 * Checks whether the <code>String</code> represents a date or not.
 * in a simple way.
 */
String.prototype.isDate = function () {
  return this.search(/^((([0][1-9])|([12][0-9])|([3][01]))|([1-9]{1}))\.((([0][1-9])|([1][0-2]))|([1-9]{1}))\.[1-9]\d{3}$/) != -1;
};

/**
 * Converts the date-<code>String</code> dd.mm.yyyy to a stringdate yyyymmdd.
 */
String.prototype.toStringDate = function () {
  if (!this.isDate()) {
    return null;
  }
  var tmp = this.split(".");
  if (tmp[0].length == 1) {
    tmp[0] = "0" + tmp[0];
  }
  if (tmp[1].length == 1) {
    tmp[1] = "0" + tmp[1];
  }
  return tmp[2] + tmp[1] + tmp[0];
};

/**
 * Converts the date to a stringdate yyyymmdd.
 */
Date.prototype.toStringDate = function () {
  var year = this.getFullYear().toString();
  var month = (this.getMonth()+1).toString();
  if (month.length == 1) {
    month = "0" + month;
  }
  var day = this.getDate().toString();
  if (day.length == 1) {
    day = "0" + day;
  }
  return year + month + day;
};

/*************************************
 * Public accessible general Methods
 *************************************/

function appendStyleRule(ruleSet, doc) {
  var tmpdoc = (doc == null) ? document: doc;
  if (tmpdoc.styleSheets) {
    if (tmpdoc.styleSheets.length == 0) {
      appendStyleElement(tmpdoc);
    }
    if (tmpdoc.styleSheets.length > 0) {
      if (tmpdoc.styleSheets[0].insertRule) {
        try {
          tmpdoc.styleSheets[tmpdoc.styleSheets.length - 1].
            insertRule(ruleSet, tmpdoc.styleSheets[0].cssRules.length);
        } catch (e) {
          tmpdoc.styleSheets[tmpdoc.styleSheets.length - 1].
            insertRule(ruleSet, 0);
        }
      } else if (tmpdoc.styleSheets[0].addRule) {
        var ruleSetPattern   = /(.*)({([^}]*)})/;
        var ruleSetPatternAt = /([\w\W]+)(\s)([\w\W]+)/;
        var match   = ruleSetPattern.exec(ruleSet);
        var matchAt = ruleSetPatternAt.exec(ruleSet);
        if (match) {
          var selector     = match[1];
          var declarations = match[3];
          tmpdoc.styleSheets[tmpdoc.styleSheets.length - 1].
            addRule(selector, declarations);
        }
        if (matchAt) {
          var selector     = matchAt[1];
          var declarations = matchAt[2];
          tmpdoc.styleSheets[tmpdoc.styleSheets.length - 1].
            addRule(selector, declarations);
        }
      }
    }
  }
}
/*************************************
 * Public accessible general Methods
 *************************************/

function appendStyleRule(ruleSet, doc) {
  var tmpdoc = (doc == null) ? document: doc;
  if (tmpdoc.styleSheets) {
    if (tmpdoc.styleSheets.length == 0) {
      appendStyleElement(tmpdoc);
    }
    if (tmpdoc.styleSheets.length > 0) {
      if (tmpdoc.styleSheets[0].insertRule) {
        try {
          tmpdoc.styleSheets[tmpdoc.styleSheets.length - 1].
            insertRule(ruleSet, tmpdoc.styleSheets[0].cssRules.length);
        } catch (e) {
          tmpdoc.styleSheets[tmpdoc.styleSheets.length - 1].
            insertRule(ruleSet, 0);
        }
      } else if (tmpdoc.styleSheets[0].addRule) {
        var ruleSetPattern   = /(.*)({([^}]*)})/;
        var ruleSetPatternAt = /([\w\W]+)(\s)([\w\W]+)/;
        var match   = ruleSetPattern.exec(ruleSet);
        var matchAt = ruleSetPatternAt.exec(ruleSet);
        if (match) {
          var selector     = match[1];
          var declarations = match[3];
          tmpdoc.styleSheets[tmpdoc.styleSheets.length - 1].
            addRule(selector, declarations);
        }
        if (matchAt) {
          var selector     = matchAt[1];
          var declarations = matchAt[2];
          tmpdoc.styleSheets[tmpdoc.styleSheets.length - 1].
            addRule(selector, declarations);
        }
      }
    }
  }
}

function appendStyleElement(doc, href) {
  var tmpdoc = (doc == null) ? document : doc;
  if (tmpdoc.createElement) {
    var styleElement = (href == null) ? tmpdoc.createElement("style") :
                                        tmpdoc.createElement("link");
    if (styleElement) {
      styleElement.type = "text/css";
      if (href != null) {
        styleElement.rel  = "stylesheet";
        styleElement.href = href;
      }
      var he = tmpdoc.getElementsByTagName("head")[0];
      if (he == null) {
        he = tmpdoc.createElement("head");
        tmpdoc.documentElement.
          insertBefore(he, tmpdoc.documentElement.firstChild);
      }
      he.appendChild(styleElement);
    }
  }
}

function intCheck(ev) {
	if (ev == null && event != null) {
		ev = event;
	}

  var code = ev.which != null ? ev.which : ev.keyCode;

  if (code == 0 || code == 13 || code == 8) {
  	return true;
  }

  return String.fromCharCode(code).isInt();
}

function floatCheck(ev) {
	if (ev == null && event != null) {
		ev = event;
	}

  var code = ev.which != null ? ev.which : ev.keyCode;

  if (code == 0 || code == 13 || code == 8 ||
      (code == 46 && ev.target.value != "" && ev.target.value.isInt())) {
  	return true;
  }

  return String.fromCharCode(code).isInt();
}

function dateDayCheck(ev) {
	if (ev == null && event != null) {
		ev = event;
	}

  var code = ev.which != null ? ev.which : ev.keyCode;

  if (code == 0 || code == 13 || code == 8) {
  	return true;
  }

  var tmp = ev.target.value + String.fromCharCode(code);
  return tmp.isInt() && parseInt(tmp) < 32;
}

function dateMonthCheck(ev) {
	if (ev == null && event != null) {
		ev = event;
	}

  var code = ev.which != null ? ev.which : ev.keyCode;

  if (code == 0 || code == 13 || code == 8) {
  	return true;
  }

  var tmp = ev.target.value + String.fromCharCode(code);
  return tmp.isInt() && parseInt(tmp) < 13;
}

/**
 * check if the pressed button belongs to a valid "it-could-be-a-date"-string.
 *
 * usage:
 *  <input type="text"
 *         size="10"
 *         class="text"
 *         id="my_start_date"
 *         maxlength="10"
 *         onkeypress="return dateCheck(event, this);"
 *         onblur="unfocusDateCheck(this);"/>
 */
function dateCheck(ev, target) {
	if (ev == null && event != null) {
		ev = event;
	}

  var code = ev.which != null ? ev.which : ev.keyCode;

  if (code == 0 || code == 13 || code == 8) {
  	return true;
  }

  if (!String.fromCharCode(code).isInt() && String.fromCharCode(code) != '.') {
  	return false;
  }

  var tmp = null;
  if (document.selection) {
    var oldval = target.value;
    var range  = document.selection.createRange();
self.status = "range.text='"+range.text+"'";
    //if (range.text != '');
      range.text = String.fromCharCode(code);
    tmp        = target.value;
self.status += " range.text='"+range.text+"'";
    target.value = oldval;
self.status += " oldvar='"+oldval+"'"+" target.value='"+target.value+"' '"+tmp+"'";
  } else {
    var selStart = ev.target.selectionStart;
    var selEnd   = ev.target.selectionEnd;
    var oldval   = ev.target.value;
    tmp          = oldval.substring(0,selStart) + String.fromCharCode(code) +
                   oldval.substring(selEnd);
  }

  var parts = null;
  if (tmp.indexOf('.') == -1) {
  	parts = [tmp];
  } else {
  	parts = tmp.split('.');
  }

  var isok = true;
  for (var l=0; l<parts.length; l++) {
    switch (l) {
      case 0 :
        if (!(parts[0].isInt() && parts[0].length < 3 && parseInt(parts[0]) < 32 &&
              !(parseInt(parts[0]) == 0 && parts[0].length == 2))) {
          isok = false;
        }
        break;
      case 1 :
        if (!(parts[1].isInt() && parts[1].length < 3 && parseInt(parts[1]) < 13 &&
            !(parseInt(parts[1]) == 0 && parts[1].length == 2)) &&
            (parts[1].length != 0 || parseInt(parts[0]) == 0)) {
          isok = false;
        }
        break;
      case 2 :
        if ((!(parts[2].isInt() && parts[2].length < 5 && parseInt(parts[2]) != 0) &&
            parts[2].length != 0) || parts[1].length == 0 || parseInt(parts[1]) == 0) {
          isok = false;
        }
        break;
      default :
        isok = false;
    }
  }
  return isok;
}

function unfocusDateCheck(element) {
	if (element == null) {
		element = this;
	}

  if (!element.value.isDate() && !isEmpty(element.value)) {
    element2focus = element;
    setTimeout("element2focus.select();",50);
  }
}

function isEmpty(value) {
  return (value == null || value.trim() == "");
}

/**
	* Adds an event to a specified object.
	*
	* @param obj the object to attach the event-listener
	* @param evType the type of the event which the listener should listen to
	* @param fn the listener-function
	*/
function addEvent(obj, evType, fn) {
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}

function getElementPosition(elem) {
	var curleft = curtop = 0;

	if (elem && elem.offsetParent) {
		do {
			curleft += elem.offsetLeft;
			curtop += elem.offsetTop;
		} while (elem = elem.offsetParent);
	}

	return [curleft, curtop];
}

function overlayBrowseButton(buttonId) {
	var browseButtonText = null;
	if (window.texts != undefined && texts.browse != undefined) {
		browseButtonText = texts.browse;
	}
	if (browseButtonText == null) {
		if (window.browseButtonText != undefined) {
			browseButtonText = window.browseButtonText;
		}
		if (browseButtonText == null) {
			browseButtonText = "Browse...";
		}
	}

	var button = document.getElementById(buttonId);
	var oldParent = button.parentNode;

	var hidden = button.getAttribute("hidden") == "true";
	var parentDiv = document.createElement("div");
	parentDiv.style.position = "relative";
	parentDiv.style.display = hidden ? "none" : "inline";

	var browseButton = document.createElement("input");
	browseButton.type = "button";
	browseButton.value = browseButtonText;
	browseButton.style.padding = "0 5px";
	browseButton.style.overflow = "visible";
	browseButton.style.borderStyle = "outset";
	browseButton.style.cursor = "default";
	if (button.disabled) {
		browseButton.disabled = true;
	}
	parentDiv.appendChild(browseButton);

	var buttonDiv = document.createElement("div");
	buttonDiv.style.position = "absolute";
	buttonDiv.style.left = "0";
	buttonDiv.style.top = "0";
	buttonDiv.style.overflow = "hidden";
	buttonDiv.style.opacity = "0";
	buttonDiv.style.filter = "alpha(opacity=0)";
	parentDiv.appendChild(buttonDiv);

	oldParent.replaceChild(parentDiv, button);
	buttonDiv.appendChild(button);

	var width = browseButton.offsetWidth;
	var height = browseButton.offsetHeight;

	buttonDiv.style.width = width + "px";
	buttonDiv.style.height = height + "px";

	button.size = "1";
	//button.style.direction = "rtl";
	button.style.fontSize = "3em";
	button.style.position = "absolute";
	button.style.left = "-100px";
	button.style.width = (width + 100) + "px";
	button.style.height = "100%";
	button.style.cursor = "default";
	button.style.display = "";

	button.refreshBorder = function(borderStyle) {
		this.browseButton.style.borderStyle = borderStyle;
	};
	button.browseButton = browseButton;
	button.onmouseout = new Function("document.getElementById(\"" + buttonId + "\").refreshBorder(\"outset\");");
	button.onmousedown = new Function("document.getElementById(\"" + buttonId + "\").refreshBorder(\"inset\");");
	button.onmouseup = new Function("document.getElementById(\"" + buttonId + "\").refreshBorder(\"outset\");");
}

function showNodeContent(node, onlyGetText, indent) {
	if (!indent) {
		indent = "";
	}
	var nodeStr = indent + "<" + node.nodeName.toLowerCase();
	if (node.attributes) {
		var attr = null;
		for (var i=0; i<node.attributes.length; i++) {
			attr = node.attributes[i];
			if (attr.nodeValue != null && attr.nodeValue.length > 0) {
				nodeStr += " " + attr.nodeName + "=\"" + attr.nodeValue + "\"";
			}
		}
	}
	if (node.childNodes.length > 0 || node.nodeValue != null) {
		nodeStr += ">\n\r";
		if (node.nodeValue != null) {
			nodeStr += indent + "  " + node.nodeValue + "\n\r";
		}
		if (node.childNodes.length > 0) {
			for (var i=0; i<node.childNodes.length; i++) {
				nodeStr += showNodeContent(node.childNodes[i], true, indent + "  ");
			}
		}
		nodeStr += indent + "</" + node.nodeName.toLowerCase() + ">\n\r";
	} else {
		nodeStr += "/>\n\r";
	}

	if (!onlyGetText) {
		var b = document.getElementById("body");
		if (b) {
			var pane = document.createElement("div");
			pane.style.position = "absolute";
			pane.style.left = "10px";
			pane.style.top = "10px";
			pane.style.width = (b.clientWidth - 20) + "px";
			pane.style.height = (b.clientHeight - 20) + "px";
			pane.style.backgroundColor = "#ffeeee";
			pane.style.overflow = "auto";

			var title = document.createElement("div");
			title.style.position = "fixed";
			title.style.left = (b.clientWidth - 20 - 110) + "px";
			title.style.top = "10px";
			title.style.width = "100px";
			title.style.height = "20px";
			title.style.backgroundColor = "#aaaaaa";
			title.style.cursor = "pointer";
			title.style.textAlign = "center";
			title.onclick = function (e) {
				if (!e) {
					e = event;
				}
				var elem = e.target || e.srcElement;
				elem.parentNode.parentNode.removeChild(elem.parentNode);
			};
			title.appendChild(document.createTextNode("close"));

			var pre = document.createElement("pre");
			pre.style.fontSize = "12px";

			pre.appendChild(document.createTextNode(nodeStr));

			pane.appendChild(title);
			pane.appendChild(pre);
			document.body.appendChild(pane);
		} else {
			alert(nodeStr);
		}
	} else {
		return nodeStr;
	}
}

function showObjectContent(elem, filter) {
	var str = "";
	if (!filter) {
		filter = "";
	}
	for (i in elem) {
		if (i.toLowerCase().indexOf(filter.toLowerCase()) != -1) {
			str += i + ": " + elem[i] + "\n\r";
		}
	}
	var b = document.getElementById("body");
	if (b) {
		var pane = document.createElement("div");
		pane.style.position = "absolute";
		pane.style.left = "10px";
		pane.style.top = "10px";
		pane.style.width = (b.clientWidth - 20) + "px";
		pane.style.height = (b.clientHeight - 20) + "px";
		pane.style.backgroundColor = "#ffeeee";
		pane.style.overflow = "auto";
		pane.id = "showObjectContentDiv";

		var title = document.createElement("div");
		title.style.position = "fixed";
		title.style.left = (b.clientWidth - 20 - 110) + "px";
		title.style.top = "10px";
		title.style.width = "100px";
		title.style.height = "20px";
		title.style.backgroundColor = "#aaaaaa";
		title.style.cursor = "pointer";
		title.style.textAlign = "center";
		title.onclick = function (e) {
			if (!e) {
				e = event;
			}
			var elem = e.target || e.srcElement;
			elem.parentNode.parentNode.removeChild(elem.parentNode);
		};
		title.appendChild(document.createTextNode("close"));

		var pre = document.createElement("pre");
		pre.style.top = "20px";
		pre.style.fontSize = "12px";

		pre.appendChild(document.createTextNode(str));

		pane.appendChild(title);
		pane.appendChild(pre);
		document.body.appendChild(pane);
	} else {
		alert(str);
	}
}

/**
 * Cookie functions
 **/
function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) {
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}
