﻿
//----------------------------------------------------------------------------------------------------
// Browser
//----------------------------------------------------------------------------------------------------
function Browser()
{
  var agent  = navigator.userAgent.toLowerCase();
  this.ns    = ((agent.indexOf('mozilla')   !=   -1) &&
                ((agent.indexOf('spoofer')   ==   -1) &&
                (agent.indexOf('compatible') ==   -1)));
  this.ie    = (agent.indexOf("msie")       !=   -1);
  this.safari = (agent.indexOf("safari")       !=   -1);
};
var browser = new Browser();

// add ESC function
if(browser.ie) {
  window.onload = __onLoad;
  document.onkeydown = __onKeyPress;
  document.onclick = __onClick;
} else {
  document.addEventListener("DOMContentLoaded", __onLoad, false);
  document.addEventListener("keydown", __onKeyPress, false);
  document.addEventListener("click", __onClick, false);
}

var debug = false;
var aLanguage = new Array();

//----------------------------------------------------------------------------------------------------
// Events
//----------------------------------------------------------------------------------------------------
function __onLoad()
{
  try {
    onInit();    
  } catch(e) {}
}

function __onClick()
{
  try {
    onClick();    
  } catch(e) {}
}

function __onKeyPress(e)
{
  var evt = null;
  
  if(browser.ie)
    evt = window.event;
  else
    evt = e;
    
  // Escape schließt Fenster  
  if(evt.keyCode == 27) {
    try {
      top.window.close();
      return;
    } catch(Error) {}
  }

  // Ctrl+S
  if(evt.keyCode==83 && evt.ctrlKey) {
    try {
      onSave();
      return;
    } catch(Error) {}
  }

  // F5
  if(evt.keyCode==116) {
    try {
      onF5();
      return;
    } catch(Error) {}
  }
}

var keyHandlers = new Array();
var blurHandlers = new Array();

// Globale Script Funktionen
function addKeyHandler(objectID,keyCode,callback)
{
  keyHandlers[keyHandlers.length] = new KeyHandlerClass(objectID,keyCode,callback);
  
  if(browser.ie) {
    document.onkeydown = keyHandlerEvent;
  } else {
    document.addEventListener("keydown", keyHandlerEvent, false);
  }
}

function KeyHandlerClass(objectID,keyCode,callback)
{
  this.id = objectID;
  this.keyCode = keyCode;
  this.callback = callback;
}

function keyHandlerEvent(e)
{
  var evt = getEventObject(e);
  var source = getEventSource(e);
  
  for(var i=0;i<keyHandlers.length;i++) {
    var curKeyhandler = keyHandlers[i];
    if(evt.keyCode == curKeyhandler.keyCode && source.id == curKeyhandler.id) {
      curKeyhandler.callback(source.id);
      CancelEvent(evt);
    }
  }
}

function addBlurHandler(objectID,callback)
{
  blurHandlers[blurHandlers.length] = new BlurHandlerClass(objectID,callback);
  
  if(browser.ie) {
    document.getElementById(objectID).onblur = blurHandlerEvent;
  } else {
    document.getElementById(objectID).addEventListener("blur", blurHandlerEvent, false);
  }
}

function BlurHandlerClass(objectID,callback)
{
  this.id = objectID;
  this.callback = callback;
}

function blurHandlerEvent(e)
{
  var evt = getEventObject(e);
  var source = getEventSource(e);
  
  for(var i=0;i<blurHandlers.length;i++) {
    var curBlurHandler = blurHandlers[i];
    if(source.id == curBlurHandler.id) {
      curBlurHandler.callback(curBlurHandler.id);
      CancelEvent(evt);
    }
  }
}

//----------------------------------------------------------------------------------------------------
// Event handler
//----------------------------------------------------------------------------------------------------

function __add_event_handler(handlerObject, eventName, callback)
{
  var aVariableArguments = new Array();
  // let the first entry for event object
  aVariableArguments[aVariableArguments.length] = "";
  for (var i = 3; i < __add_event_handler.arguments.length; i++) {
    aVariableArguments[aVariableArguments.length] = __add_event_handler.arguments[i];
  }

  if (browser.ie) {
    handlerObject.attachEvent("on" + eventName, __bind(callback, aVariableArguments));
  } else {
    handlerObject.addEventListener(eventName, __bind(callback, aVariableArguments), false);
  }
}

function __bind(callback, args)
{
  return function (e)
  {
    var evt = null;
    if (this.ie)
      evt = window.event;
    else
      evt = e;
    args[0] = evt;
    callback.apply(this, args)
  };
}

function remove_event_handler(handlerObject, eventName, callback)
{
  var aVariableArguments = new Array();
  if (browser.ie) {
    handlerObject.detachEvent("on" + eventName, callback);
  } else {
    handlerObject.removeEventListener(eventName, callback, false);
  }
}

//----------------------------------------------------------------------------------------------------
// Global
//----------------------------------------------------------------------------------------------------
function globalGetPositonY(obj)
{
  var y = 0;
  var parent = obj;
  while(parent.tagName.toUpperCase() != "BODY") {
    y = y + parent.offsetTop;
    parent = parent.offsetParent;
  }
  return y;
};


function globalGetPositonX(obj)
{
  var x = 0;
  var parent = obj;
  while(parent.tagName.toUpperCase() != "BODY") {
    x = x + parent.offsetLeft;
    parent = parent.offsetParent;
  }
  return x;
};

function getEventObject(e)
{
  if(browser.ie)
		return window.event;
  else
    return e;
}

function getEventSource(e) 
{
  if(browser.ie) {
		return window.event.srcElement;
  } else {
    return e.target;
	}
};

function CancelEvent(e)
{
  if(browser.ie) {
    e.keyCode = 0; 
    e.cancelBubble = true;
    e.returnValue = false;
  } else {
    e.preventDefault();
  }
}

function openDialogWindow(width,height,url)
{
  if(browser.ie) {
     var win = window.showModalDialog(url,window,"dialogHeight:" + height + "px;dialogWidth:" + width + "px;resizable:0;status:0;scroll:0");
  } else {
    var left = screen.width/2 - width/2;
    var top = screen.height/2 - height/2;
    window.open(url,"","modal=yes,left=" + left + ",top=" + top + ",height=" + height + ",width=" + width + ",resizable=1,status=0,scrollbars=0");
  }
  return win;
}

function openWindow(width,height,url)
{
    var left = screen.width/2 - width/2;
    var top = screen.height/2 - height/2;
    var win = window.open(url,"","left=" + left + ",top=" + top + ",height=" + height + ",width=" + width + ",resizable=1,status=0,scrollbars=1");
    win.focus();
    return win;
}

function getFileName(url)
{
  var fileName = "";
  for(var i=url.length;i>0;i--) {
    if(url.substring(i,i+1) == "/") {
      fileName = url.substring(i+1);
      break;
    }
  }
  return fileName;
}


function log(p1,p2,p3)
{
  if(debug) {
    try {
      alert(p1 + ":" + p2 + ":" + p3);
      var ajax = new Ajax();
      var aParams = new Array();
      aParams[0] = ajax.createParam("param1",p1);
      aParams[1] = ajax.createParam("param2",p2);
      aParams[2] = ajax.createParam("param3",p3);
      ajax.request(webRoot + "application/server.aspx",aParams);
    } catch(e) {}
  }
}

//----------------------------------------------------------------------------------------------------
// AJAX
//----------------------------------------------------------------------------------------------------
function Ajax()
{
  this.isError     = false;
  this.method      = "POST";
  this.xml         = null;
  this.text        = "";
  this.xmlString   = "";
  this.httpRequest = null;
  this.asynchron   = true;
  this.tag         = null;

  this.request     = __app_ajax_request;
  this.response    = __app_ajax_onreadystatechange;
  this.execute     = __app_execute;
  this.createParam = __app_create_param;
  this.callback    = null; 
};

function __app_create_param(key, value)
{
  var pair = null;
  try {
    pair = new __app_pair(key, value);
  } catch(e) {
    alert("Ajax error: " + e);
  }
  return pair;
}

function __app_ajax_request(url, params) 
{
  var parameters = null;
  
  if (window.XMLHttpRequest) { 
    this.httpRequest = new XMLHttpRequest();
    if (this.httpRequest.overrideMimeType) {
      this.httpRequest.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) { 
    try {
      this.httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        this.httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }

  if (!this.httpRequest) {
    alert('Cannot create an XMLHTTP instance');
    return false;
  }

  if(this.callback != null) {
    this.httpRequest.onreadystatechange = this.execute(this);
  }

  // if we have parameters to pass then use post
  if(this.method == "POST") {
    // set header
    this.httpRequest.open('POST',url, this.asynchron);
    this.httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    // build params
    parameters = "";
    for(var i=0;i<params.length;i++) {
      if(i>0)
        parameters += "&";
      var pair = params[i];
      parameters += pair.key + "=" + encodeURIComponent(pair.value);
    }
  } else {
    this.httpRequest.open('GET',url, this.asynchron);
  }

  this.httpRequest.send(parameters);
};

function __app_execute(ajax)
{
  return function() { __app_ajax_onreadystatechange(ajax) };
}

function __app_ajax_onreadystatechange(ajax)
{
  if(ajax.httpRequest.readyState == 4) {
    if(ajax.httpRequest.status == 200) {
      // now we have data 
      ajax.isError = false;
      ajax.xml = ajax.httpRequest.responseXML;
      ajax.xmlString = ajax.httpRequest.responseXML.xml;
      ajax.text = ajax.httpRequest.responseText;
      if(ajax.callback)
        ajax.callback(ajax);
      ajax.callback = null;
    } else {
      ajax.isError = true;
    }
  }

};

function __app_pair(key, value)
{
  this.key = key;
  this.value = value;
};



//------------------------------------------------------------------------------
// Possible Validators
//------------------------------------------------------------------------------
var cEMAIL = "[a-zA-Z0-9_.-]{1,}\\@[a-zA-Z0-9_.-]{1,}\\.\\w{2,}";
var cDATE = "\\d{2}\\.\\d{2}\\.\\d{4}";
var cZIP = "\\d{5}";
var cSTREET = "[a-zA-Z0-9- )(ßÄÖÜäöü.]+";
var cNAME = "[^§'€]+";
var cPHONE = "[0-9 )(-/+]+";
var cNUMBER = "\\d{1,}";
var cFLOAT = "[0-9]{1,}\\,[0-9]{0,}";
//var cTEXT = "[a-zA-Z0-9-ßÄÖÜäöü #+!§()/&*?.-]+";
var cTEXT = "[a-zA-Z0-9_.-]+";
var cLOGIN = "[a-zA-Z0-9_.-]+";
var cPASSWORD = "[a-zA-Z0-9_.-]+";
var cSEARCH = "[a-zA-Z0-9- )(ßÄÖÜäöü.,;:*%]+";

var cDATE_E = "\\d{4}\\-\\d{2}\\-\\d{2}";
var cFLOAT_E = "[0-9]{1,}\\.[0-9]{0,}";
var cNUMBER_E = "[0-9]{1,}\\.[0-9]{1,2}";

var _lastSelected;
var _bcHighlight = "#FFCC66";
var _bcStandard = "white";

function checkFloat(field,validator,message,language)
{
  if(!check(field,cNUMBER,message,language,false)) {
          // if last char is "," then add 0
          var value = field.value;
          var last = value.substring(value.length-1,value.length)
          // if we have a german or a english format
          if(validator == cFLOAT || validator == cFLOAT_E) {
                  return check(field,validator,message,language,true);
          } else {
                  // use default
                  return check(field,cFLOAT,message,language,true);
          }
  } else {
          return true;
  }
}

// Standard validate function
function check(field, validator, message, language, isHighlight)
{
	var regEx  = new RegExp(validator);
	var match  = regEx.exec(field.value);
	var temp   = "";
	var isHigh = false;

	// if isHighlight is not set, make sure that it is true
	if(isHighlight == null) {
		isHigh = true;
	} else {
		isHigh = isHighlight;
	}

	if(_lastSelected != null)
		setBackground(_lastSelected,_bcStandard);

	if (match == null) {
		if(isHigh)
			highlight(field,message);
		return false;
	}

	temp += match;

	if(match.index == 0 && temp.length == field.value.length) {
		return true;
	} else {
		if(isHigh)
			highlight(field,message);
		return false;
	}
}

function highlight(field,message)
{
	setBackground(field,_bcHighlight);
	_lastSelected = field;
	alert(message);
	field.focus();
	field.select();
}

function checkDate(field,validator,message)
{
	var value = field.value;

	//if(value.length == 0)
	//	return false;

	if(check(field,validator,message)) {
		var day		= value.substr(0,2);
		var month	= value.substr(3,2);
		var year	= value.substr(6,4);

		if (day < 1 || day > 31) {
			highlight(field,message);
			return false;
		}

		if (month < 1 || month > 12) {
			highlight(field,message);
			return false;
		}

		if ((month==4 || month==6 || month==9 || month==11) && day==31)	{
			highlight(field,message);
			return false;
		}

		if (month == 2)	{
			var isLeap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day > 29 || (day==29 && !isLeap))	{
				highlight(field,message);
				return false;
			}
		}
	} else {
		return false;
	}
	return true;
}

function setBackground(field, value)
{
  if(browser.dom)
    field.style.background = value;
}

function isSessionExpired()
{
  var expired = 0;
  try {
    var ajax = new Ajax();
    ajax.method = "POST";
    ajax.asynchron = false;
    ajax.callback = null;
    var aParams = new Array();
    aParams[0] = ajax.createParam("key","SESSION");
    ajax.request(webRoot + "application/server.aspx?r=" + Math.random(),aParams);
    ajax.xml = ajax.httpRequest.responseXML;
    expired = ajax.xml.getElementsByTagName("expired")[0].firstChild.data;
  } catch(e) {}
  return (expired == 1) ? true:false;
}


//----------------------------------------------------------------------------------------------------
// Localisation
//----------------------------------------------------------------------------------------------------
function initLocalization(xmlPath, init)
{
  if(!xmlPath)
    xmlPath = webRoot + "application/localization/" + language + ".xml"; 
  if(init != false)
    init = true;

  // now read language file
  var xmlDoc = null;
  // load config file
  if(browser.ie) {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.load(xmlPath);
    __callback_localize(xmlDoc, init);
  } else {
//    xmlDoc = document.implementation.createDocument("", "", null);
//    xmlDoc.onload = function() { __callback_localize(xmlDoc, init);};
//    xmlDoc.load(xmlPath);
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", xmlPath, false);
    xmlhttp.send(null);
    xmlDoc = xmlhttp.responseXML.documentElement;
    __callback_localize(xmlDoc, init);
  }
}


function __callback_localize(xmlDoc,init)
{
  // read lnguage strings
  var aText = xmlDoc.getElementsByTagName("text");
  for(var i=0;i<aText.length;i++) {
    aLanguage[aText[i].getAttribute("id")] = aText[i].getAttribute("name");
  }
  
  try {
    if(init)
      afterLocalizationInit();
  } catch(e) {}
  
  // now set language dependant strings
  //__localize();
};


/*
// localize
function __localize()
{
  try {
    // set span
    var aSpan = document.getElementsByTagName("span");

    for(var i=0;i<aSpan.length;i++) {
      if(aSpan[i].id != "") {
        if(aSpan[i].id.substring(0,1) == "#")
          aSpan[i].innerHTML = getString(aSpan[i].id.substring(1));
      }
    }
    // set div
    var aDiv = document.getElementsByTagName("div");
    for(var i=0;i<aDiv.length;i++) {
      if(aDiv[i].id != "") {
        if(aDiv[i].id.substring(0,1) == "#")
          aDiv[i].innerHTML = getString(aDiv[i].id.substring(1));
      }
    }
  } catch(Error) {}
};
*/

function getString(id)
{
  var s = "";
  try {
   s = aLanguage[id]; 
  } catch(Error) {}
  return s;
};


//----------------------------------------------------------------------------------------------------
// Combo
//----------------------------------------------------------------------------------------------------
// combo functions
function comboAdd(combo,text,value,style)
{
  var item = document.createElement("option");
  item.text = text;
  item.value = value;
  if(style) {
    item.style.cssText = style;
  }
  if(browser.ie) {
    combo.add(item);
  } else {
    combo.add(item,null);
  }
}

function comboSet(combo,value)
{
  var len = combo.length;
  for(var i=0;i<len;i++) {
    if(combo.options[i].value == value) {
      combo.selectedIndex = i;
      return;
    }
  }
}

function comboClear(combo)
{
  while(combo.options.length >0) {
    combo.remove(0);
  }
}

function comboGetSelectedText(combo)
{
  var text = "";
  try {
    text = combo.options[combo.selectedIndex].text;
  } catch(e) {}
  return text;
}


