
/* 
 * Hermes Constant Sittings 
 */
 
var HERMES_SITES = {
  /* ************************************  Portal - Sites *******************************  */
  PriPS_DEU: {
 	id: 			"PriPS_DEU",
  	em_siteid: 		3,
  	publicUrl:		"privatpaketservice.hlg.de",
  	uniqueContext: 	"wps/portal/PRIPS_DEU",
  	land:			"DEU"
  },
  PriPS_AUT: {
  	id: 			"PriPS_AUT",
  	em_siteid: 		6,
  	publicUrl:		"privatpaketservice.hlg.at",
  	uniqueContext: 	"wps/portal/PRIPS_AUT",
  	land:			"AUT"
  },
  ProPS_DEU: { 
  	id: 			"ProPS_DEU",
  	em_siteid: 		2,
  	publicUrl:		"profipaketservice.hlg.de",
  	uniqueContext: 	"wps/portal/PROPS_DEU",
  	land:			"DEU"
  },
  AdminHLG: {
 	id: 			"AdminHLG",
 	em_siteid:		88,
  	publicUrl:		"",
  	uniqueContext: 	"wps/portal/ADMIN_HLG/",
  	land:			"DEU"
  },
  /* ************************************ Other Sites ***********************************  */
  Others1: {
	id: 		"hlg_de",
  	em_siteid: 	0,
  	publicUrl:	"www.hermes-logistik-gruppe.de"
  },
  Others2: { 
  	id: 		"hlg_at",
  	em_siteid: 	4,
  	publicUrl:	"hermes-logistik-gruppe.at"
  },
  Others3: { 
  	id: 		"PaketShop_DEU",
  	em_siteid: 	1,
  	publicUrl:	"www.hermespaketshop.de"
  },
  Others4: { 
  	id: 		"PaketShop_AUT",
  	em_siteid: 	5,
  	publicUrl:	"hermespaketshop.at"
  }
};

// sendungen[i].sendungsart
var HERMES_SENDUNGSART = {
	0:		"STANDARD",
	100:	"Packet",
	170:	"Fahrrad",
	180:	"ReiseGepaeck",
	190:	"SonderGepaeck",
	200:	"SKI",
	280:	"SBPAKET",
	400:	"RAK"
};

// sendungen[i].verpackung
var HERMES_VERPACKUNG = {
	100:	"FahrradVerpackung",
	110:	"SkiVerpackung"
};

/* 
 auftrag.abholung := true | false 
 auftrag.abholtermin != null -> Abholung
 auftrag.abholtermin == null -> PacketShop
*/

/* 
 * HermesValueStore
 * 	Object to store commonly portal-wide used data, 
 * 	HermesGlobalData is Singleton Instance of the object HermesValueStore
 *
 * Usage: 
 *		HermesGlobalData.set("key", value);
 *  	HermesGlobalData.get("key");
 */

function HermesValueStore(target) {
	this.initialize(target);
}

HermesValueStore.prototype.initialize = function(target) {

	    if (!target._globalHermesValueStore) {
	     	 target._globalHermesValueStore = {};
	    }
	    this.target = target;  
}

HermesValueStore.prototype.set= function(key, value) {
	    if (typeof(key) != "string") {
	      	throw { message: "HermesValueStore.setValue(): key must be a String!" };
	    }
	    value = { _value: value };
//	    var json = value.toJSONString()

	    var json = Object.toJSON(value);
	     
	    this.target[key] = json;
}

HermesValueStore.prototype.get= function(key) {
	    var value = this.target[key];
	    if (value != null) {
	      	//value = value.parseJSON()._value;
	      	value = value.evalJSON()._value;
	    }
	    return value;
}

/* bind objects an top or opener  */
var target = null;
try {
  	target = opener ? opener.top : top;
} catch (e) {}

/* Im Fall, dass die Seite von fremder Domain aufgerufen wird, ist opener.top CrossDomain 
 * und liefert somit security exception, binden wir dann also an top und nicht an opener */
try {
  	var hostname = target.location.hostname;
} catch (e) {
  	target=top;
}

if (target == null) {
  	target = top;
}

var HermesGlobalData = new HermesValueStore(target);

/* Set some Constants */
 HermesGlobalData.set( "HERMES_SITES", HERMES_SITES);
 HermesGlobalData.set( "HERMES_SENDUNGSART", HERMES_SENDUNGSART);
 HermesGlobalData.set( "HERMES_VERPACKUNG", HERMES_VERPACKUNG); 

	    
/*
 * CommonUtils Object encapsulates various static utility functions
 * portal-wide useable
 */

var HermesCommonUtils = {

  loggingEnable:	false,
  
  setLogging: function() {
 	if (!window.HermesGlobalData)	{ return; }
 	
  	HermesGlobalData.set("LOGGING",false);
  	if ( HermesGlobalData.get("MODE") == "test" || HermesGlobalData.get("MODE") == "dev") {
  		if (window.console) {
	  		HermesGlobalData.set("LOGGING", true);
	  		this.loggingEnable=true;
	  	}
  	}
  },
  
  log: function (str, level, objs) {
  	if (!this.loggingEnable) { return; }
  	if (!window.console) 	 { return; }	/* Logging only for FireBug or Safari DebugWindow */
  	if (!str)				 { return; }
  	
  	if (!level)	{ 
  		level="log"; 	/* Default */
  	}
  	
  	/*
	  	if ( !level.match(/info|warn|err|debug/)) {
	  		level="log"; 
	  	} 
  	*/
  	if (!objs) {
	  	if (level.match(/debug/)) {
	  		console.debug(str);
	  	} else if (level.match(/info/)) {
	  		console.info(str);
	  	} else if (level.match(/warn/)) {
	  		console.warn(str);
	  	} else if (level.match(/err/)) {
	  		console.error(str);
	  	} else {
	  		console.log(str);
	  	}
  	} else {
	  	if (level.match(/debug/)) {
	  		console.debug(str,objs);
	  	} else if (level.match(/info/)) {
	  		console.info(str,objs);
	  	} else if (level.match(/warn/)) {
	  		console.warn(str,objs);
	  	} else if (level.match(/err/)) {
	  		console.error(str,objs);
	  	} else {
	  		console.log(str,objs);
	  	}
	}
  },
  
  showObj: function (obj) {
  	if (!this.loggingEnable) { return; }
	console.dir(obj)
  },
  
 /* Returns true if eMail parameter is of valid eMail-Address Syntax,
  * false otherwise
  */
  checkEmailSyntax:	function(email) {
		// Umlaute als Unicode, um js Datei auch  ohne charset=ISO-8859-1 einbinden zu koennen
		var	pattern = /^[\w\u00E4\u00C4\u00F6\u00D6\u00FC\u00DC\u00EB\u00CB\u00DF\-\.]+@([\w\u00E4\u00C4\u00F6\u00D6\u00FC\u00DC\u00EB\u00CB\u00DF\-]{1,63}\.)+[a-zA-Z]{2,6}$/;
		if (email && pattern.test(email)){
				return true;
		}
		return false;
  },
  
  testEmails: function() {
     var addrs= new Array("h.d@x.com", "-@ww.de", "aa-bb-cc.cb@Uuuuu.com", "a@d3e","a@ddd.c",
     					  "a@ddd.ccccccc", "s...c@localhost", "x@127.0.0.0", "x@a....com"); 
     for (var i=0; i<addrs.length; i++) {
         var email=addrs[i];
         var cm = this.checkEmailSyntax(email);
         document.writeln("email=" + email + " check=" + cm + "<br />");        
     }
  },
  
 /* Returns true, if all is printable, i.e.
  * if string parameter does not contain control-characters,
  * false otherwise
  *
  * schoen beschrieben in http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
  * zum Testen Leerzeichen rausnehmen
  */
  checkForControlCharacters: function (string) {
   /*
		String pattern = "^[\\p{Graph}\\s]*$"; 
		if (!content.matches(pattern)) {
			// error
		}
	*/
   	return true;
  },
  
  /* 
   *  Trims a String and returns the trimed string 
   */
   trim: function (str) {
  	var res = str.replace(/^[\s\n]*/,"");
  	res = res.replace(/[\s\n]*$/,"");
  	res=res.replace(/\n/g,"");
  	return (res);
  },

  /*
   * Formatierte Ausgabe von Fliesskommazahlen
   * Parameter:
   *	number: (float)  zu formatierende Zahl
   *	laenge: (int)	 Anzahl Nach-Komma Stellen 
   * 	sep:	(String) Dezimal-Separator ('.' or ',' etc.)
   *	th_sep	(string) Thousend-Separator
   * Return:	(string) The formated Number
   */
   number_format: function (number, laenge, sep, th_sep ) {
	  number = Math.round( number * Math.pow(10, laenge) ) / Math.pow(10, laenge);
	  str_number = number+"";
	  arr_int = str_number.split(".");
	  if(!arr_int[0]) arr_int[0] = "0";
	  if(!arr_int[1]) arr_int[1] = "";
	  if(arr_int[1].length < laenge){
	    nachkomma = arr_int[1];
	    for(i=arr_int[1].length+1; i <= laenge; i++){  nachkomma += "0";  }
	    arr_int[1] = nachkomma;
	  }
	  if(th_sep != "" && arr_int[0].length > 3){
	    Begriff = arr_int[0];
	    arr_int[0] = "";
	    for(j = 3; j < Begriff.length ; j+=3){
	      Extrakt = Begriff.slice(Begriff.length - j, Begriff.length - j + 3);
	      arr_int[0] = th_sep + Extrakt +  arr_int[0] + "";
	    }
	    str_first = Begriff.substr(0, (Begriff.length % 3 == 0)?3:(Begriff.length % 3));
	    arr_int[0] = str_first + arr_int[0];
	  }
	  return arr_int[0]+sep+arr_int[1];
  },
  
	
  openPopUpWindow: function (link, name, width, height,left,top) {
	/*
	alert ("in openPopUpWindow " + 
		"\nlink: "+ link + 
		"\nname: "+ name + 
		"\nwidth: "+ width +
		"\nheight: " + height +
		"\nleft: " + left +
		"\ntop: "+ top); 
	*/
	teststr = "width="+width+", height="+height+", left="+left+", top="+top;
	//alert(teststr);
	win = window.open(link, name, teststr);
	win.focus();
  },
  
  /* ****************************** Layer-Control ********************************************* */
  
   /* ** Show Layer with id layerId on Position with id positionId ** */
   showLayer: function ( layerId, positionId ) {
	  if (!layerId || !positionId) return;
	  var layer     = document.getElementById ( layerId );
	  var pos       = document.getElementById ( positionId );
	  var posLeft = this.getLeft(pos);
	  var posTop =  this.getTop(pos);
	  if (layer) {
	        layer.style.left = posLeft + "px";
	        layer.style.top  = posTop + "px";
	        layer.style.visibility = 'visible';
	  }
	  return;
   },
	
   /* ** Show Layer with id layerId on Position posX, posY ** */
   showLayerXY: function ( layerId, posX, posY ) {
	  if (!layerId) return;
	  var layer     = document.getElementById ( layerId );
	  if (layer) {
	        layer.style.left = posX + "px";
	        layer.style.top  = posY + "px";
	        layer.style.visibility = 'visible';
	  }
	  return;
	},
	
	/* ******** Hide Layer with id layerId          ******************* */
	hideLayer: function (layerId) {
	  if ( !layerId) return;
	  var layer = document.getElementById ( layerId );
	  if ( layer )  layer.style.visibility = "hidden";
	  return;
	},
	
	/* ******** Get left Position of Element l      ******************* */
	getLeft: function (l) {
	  if ( !l ) return 0 ;
	  if (l.offsetParent) return (l.offsetLeft + this.getLeft(l.offsetParent));
	  else return (l.offsetLeft);
	},
	
	/* ******** Get top Position of Element l       ******************* */
	getTop: function (l) {
	  if ( !l ) return 0 ;
	  if (l.offsetParent) return (l.offsetTop + this.getTop(l.offsetParent));
	  else return (l.offsetTop);
	},
	
	/* Fits the Value of Text-Fields acourding its length 
	 * (wenn value laenger als maxlength, stellt IE  nicht dar)
	 */
	fitTextFields: function ( fieldIds) {
      for (var fieldId in fieldIds) {  
	       var field = document.getElementById(fieldIds[fieldId]);
	       if (field) {
		       if ( field.value.length > field.maxLength) {
		          field.value = field.value.substr(0,field.maxLength);
		       }
	       }
      }
    },
    
    
	/*
	 * Returns the object, initing the event
	 */
  	getEventElement: function (event) {	
	    if(event == null) {
			 event = window.event;
			 event.currentTarget = event.srcElement;
			 while(event.currentTarget.nodeName.toLowerCase() != "tr") {
			   event.currentTarget = event.currentTarget.parentNode;
			 }
			 event.cancelBubble = true;
   		} else {
			event.stopPropagation();
		}
		return event.currentTarget;
	},
	
	/*
	 *  Returns an Array of the style class of the element
	 */
	getClasses: function (element) {
    	if(element.className) {
     		return element.className.match(/[^ \t\n\r]+/g);
    	} else {
     		return new Array(0);
    	}
  	},
  	
  	/*
  	 * Sets the selected Index of an Selectbox
  	 * value shoult be the value of the option to set
  	 */ 
  	setSelected: function (selectedElem, value) {
  		if (!selectedElem) { return; }
  		if (!selectedElem.options) { return; }
  		
  		var options=selectedElem.options ;
		for (var i = 0; i< options.length ; i++){
          var optValue = options[i].value ;
          if (optValue.indexOf(value) != -1) {
          	options[i].selected = true;
          	options[i].defaultSelected = true;
          	selectedElem.selectedIndex=i;
          	break;
          }
        }
  	},
  	
  	WindowOnloadListe: [],
  	
  	windowOnLoad: function() {
  		HCU.log("HCU windowOnLoad. Len of HCU.WindowOnloadListe  ="+ HCU.WindowOnloadListe.length);
		var wol = HCU.WindowOnloadListe;
        for (var i=0;i<wol.length;i++){
			wol[i].func.apply(wol[i].thisObj, wol[i].argArray );
        } 
        
       // // scroll for content-portlets to top
       // if ($("content")) {
	   //    window.scrollTo(1, 1);
	   //}
        
  	}
    
};
var HCU = HermesCommonUtils;
window.onload=HermesCommonUtils.windowOnLoad;


/******************** DisplayTag Extensions **********************************************/
	function DTHandler (pageNr, pageSize) {
		this.pageNr = pageNr;
		this.pageSize = pageSize;
		this.lineNr = this.pageNr * this.pageSize ;
	};
	
	/* Extension for line numbering */
	DTHandler.prototype.setLineNumber = function (id) {
		HCU.log("id="+id);
		this.lineNr = this.lineNr + 1 ;
		$(id).innerHTML = this.lineNr;
	};
	
	/* Placement of pagesize Select */
	DTHandler.prototype.showPageSizeSelect = function (selectId) {
		// HermesCommonUtils.showLayer(selectId, "pagesize");
		// HCU.WindowOnloadListe.append( {func:DTh.showPageSizeSelect, thisObj:this, argArray:["maxRowsOben"]} );
		HCU.WindowOnloadListe.append( {func:HermesCommonUtils.showLayer, thisObj:HCU, argArray:[selectId, "pagesize"]} );
	};
	
/******************** Array Extension **************************************************/
 Array.prototype.indexOf=function(obj){
	var result=-1;
	for (var i=0;i<this.length;i++){
		if (this[i]==obj){
			result=i;
			break;
		}
	}
	return result;
 };
 Array.prototype.contains=function(obj){
	return (this.indexOf(obj)>=0);
 };
 Array.prototype.append=function(obj,nodup){
	if (!(nodup && this.contains(obj))){
		this[this.length]=obj;
	}
 };



HermesDialog = Class.create();

HermesDialog.prototype = {

  initialize: function(dialogId, title, message) {
    this.id = dialogId;
    this.title = title;
    this.message = message;
  },

  show: function(paramMap, modal) {
	    var defaultParams = {
			title:      this.title,
			width:		390,
			height:		200,
			closable:   true,
			minimizable: false,
			maximizable: false,
			resizable:  false,
			draggable:	true,
			buttons:	[],
			messageType: "INFO",
	 		onClose:	Prototype.emptyFunction
	    };
	    var params = Object.extend(defaultParams,paramMap);
	    params.title="<span style='margin-top:4px;padding-top:4px;top:3px;'> "+params.title + "</span>";
	
	    this.win = new Window(this.id, params);
	    this.win.getContent().innerHTML = this._createContent(params.buttons, params.messageType);
	    this.win.setDestroyOnClose();
	    this.win.showCenter(modal);
	    this.win.centered = true;
	    try {
		    this._initButtonEventHandlers(params.buttons);
		    if (this.focusedButton) {
		    	this.focusedButton.focus();
		    }
	    } catch (e) {
	    	alert("Exception: " + e.getMessage); 
	    }
  },

  _iconTd: "",
  
  _createContent: function(buttons, messageType) {
  		var tableStyle="cellpadding=10 cellspacing=10  align='center' ";  
  		if (messageType == "ERROR") {
  			this._iconTd = "<td style='vertical-align:middle;'><div class='errorIcon'> </div</td>";
  		}
		msgBodyContent = " <table " + tableStyle + " width='100%'> <tr> " + this._iconTd + "<td class='dialog_content'>" + this.message + "</td> </tr> </table>";
		
		var buttonContent = " <table " + tableStyle + " > <tr>";
		for (var i = 0; i < buttons.length; i++) {
			  var button = buttons[i];
			  // text-decoration:underline;
			  buttonContent += "<td><input id='" + button.buttonClass + "_button' \
			  	class='wpsButtonText " + button.buttonClass + "' type='button'";
			  if(button.style != null && button.style.length >0){
			      buttonContent += " style=" + button.style;
			  }
			  buttonContent += " value='" + button.caption + "'/> </td>";
		}
		buttonContent += "</tr></table>";
		
		var content = "\
		  <div id='" + this.id + "_div' > \
		    <div class='dialog_message' >" + msgBodyContent + " </div> \
		    <div class='dialog_buttons' >"  + buttonContent + "  </div> \
		  </div>";
		
		return content;
  },

  
  /* Button Click Function */
  clickAndClose: function(e) {
  	// var buttonCtx = this;
  	var event = e;
  	this.onclickFct(e);
  	this.win.close();
  },
  
  _initButtonEventHandlers: function(buttons) {
	    for (var i = 0; i < buttons.length; i++) {
			    var button = buttons[i];
				var buttonElem = $(button.buttonClass + "_button");
				if (button.onclick) {
					buttonElem.onclickFct=button.onclick;
				} else {
					buttonElem.onclickFct=Prototype.emptyFunction;
				}
				buttonElem.onclick=this.clickAndClose;
				buttonElem.win = this.win;
	    }
	    
	    // Default Button 
	    for (var i = 0; i < buttons.length; i++) {
	   		    var button = buttons[i];
	   			var buttonElem = $(button.buttonClass + "_button");
	     		if ( button.isDefault) {
					this.focusedButton = buttonElem;
					buttonElem.focus();
				}
	    }
	    
	    // TODO: KeyCodes
  }

};


